Exception
fastapi.BackgroundTasks exception not caught
Stack trace
Traceback (most recent call last):
File "/usr/local/lib/python3.10/site-packages/starlette/background.py", line 45, in _run
await self.func(*self.args, **self.kwargs)
File "/app/tasks.py", line 12, in background_task
raise ValueError("Something went wrong in background task")
ValueError: Something went wrong in background task
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.10/site-packages/uvicorn/protocols/http/h11_impl.py", line 429, in run_asgi
result = await app( # type: ignore[func-returns-value]
File "/usr/local/lib/python3.10/site-packages/fastapi/applications.py", line 276, in __call__
await super().__call__(scope, receive, send)
File "/usr/local/lib/python3.10/site-packages/starlette/applications.py", line 122, in __call__
await self.middleware_stack(scope, receive, send)
File "/usr/local/lib/python3.10/site-packages/starlette/middleware/errors.py", line 184, in __call__
raise exc
File "/usr/local/lib/python3.10/site-packages/starlette/middleware/errors.py", line 162, in __call__
await self.app(scope, receive, _send)
File "/usr/local/lib/python3.10/site-packages/starlette/middleware/exceptions.py", line 79, in __call__
raise exc
File "/usr/local/lib/python3.10/site-packages/starlette/middleware/exceptions.py", line 68, in __call__
await self.app(scope, receive, sender)
File "/usr/local/lib/python3.10/site-packages/starlette/routing.py", line 718, in __call__
await route.handle(scope, receive, send)
File "/usr/local/lib/python3.10/site-packages/starlette/routing.py", line 276, in handle
await self.app(scope, receive, send)
File "/usr/local/lib/python3.10/site-packages/starlette/routing.py", line 69, in app
await func(request)
File "/app/main.py", line 25, in endpoint
background_tasks.add_task(background_task)
File "/usr/local/lib/python3.10/site-packages/starlette/background.py", line 54, in _run
raise exc
Exception: Something went wrong in background task Why it happens
FastAPI runs background tasks asynchronously after returning the response, but exceptions raised inside these tasks are not automatically caught or propagated to the main request lifecycle. This causes unhandled exceptions that do not trigger standard error handling or logging.
Detection
Monitor logs for uncaught exceptions in background tasks or wrap background task functions with try/except blocks to catch and log exceptions explicitly before they cause silent failures.
Causes & fixes
Background task function raises an exception that is not caught inside the task.
Wrap the background task code in try/except blocks to catch exceptions and log or handle them appropriately.
No global error handler or middleware configured to catch exceptions from background tasks.
Implement custom exception handling inside background tasks or use event hooks to log errors from background tasks.
Background task added without awaiting or monitoring its completion, causing exceptions to be lost.
Use background task frameworks or libraries that support error callbacks or await task completion when possible.
Code: broken vs fixed
from fastapi import FastAPI, BackgroundTasks
app = FastAPI()
def background_task():
# This will raise an exception that is not caught
raise ValueError("Something went wrong in background task")
@app.post("/run-task")
async def run_task(background_tasks: BackgroundTasks):
background_tasks.add_task(background_task) # Exception here is not caught
return {"message": "Task started"} import os
from fastapi import FastAPI, BackgroundTasks
import logging
app = FastAPI()
logging.basicConfig(level=logging.ERROR)
def background_task():
try:
# Exception is caught and logged
raise ValueError("Something went wrong in background task")
except Exception as e:
logging.error(f"Background task error: {e}")
@app.post("/run-task")
async def run_task(background_tasks: BackgroundTasks):
background_tasks.add_task(background_task) # Now exceptions are caught inside task
return {"message": "Task started"}
# This fix adds try/except inside the background task to catch exceptions and log them. Workaround
Wrap the background task function in try/except and log exceptions; alternatively, run the task synchronously during development to catch errors immediately.
Prevention
Design background tasks with internal exception handling and logging, or use task queues (e.g., Celery) that provide robust error handling and retries outside FastAPI's background task system.