asyncio.CancelledError: Task Was Cancelled

asyncio.CancelledError

Quick Answer

An asyncio task was cancelled while running. Handle CancelledError for cleanup, but always re-raise it so cancellation completes.

Why This Happens

When you call task.cancel(), the task receives CancelledError at the next await point. Catch it for cleanup (closing connections, saving state), but re-raise to complete cancellation.

The Problem

async def worker():
    while True:
        await asyncio.sleep(1)
        print('working')

task = asyncio.create_task(worker())
task.cancel()
await task  # Raises CancelledError

The Fix

async def worker():
    try:
        while True:
            await asyncio.sleep(1)
    except asyncio.CancelledError:
        print('Cleaning up...')
        raise

task = asyncio.create_task(worker())
task.cancel()
try:
    await task
except asyncio.CancelledError:
    print('Task cancelled')

Step-by-Step Fix

  1. 1

    Catch for cleanup

    Use try/except asyncio.CancelledError for cleanup.

  2. 2

    Always re-raise

    After cleanup, re-raise CancelledError.

  3. 3

    Handle at caller

    Wrap await task in try/except at the call site.

Bugsly catches this automatically

Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.

Try Bugsly free