A FastAPI yield dependency catches the endpoint's exception with except Exception and never re-raises it; what does the client get, and what do the logs show?
answer
- the exception arrives at the yield
- handled means FastAPI never sees it
- no response object to send
- "Response not awaited"
- bare raise, or a new exception
basics
~20 sIn FastAPI 0.143 the client gets a 500, even for an HTTPException, and with the default scope the log shows a FastAPIError about a response not awaited instead of the original error. End the except with raise.
solid answer
~50 sWhen the endpoint raises, FastAPI throws the exception into each yield dependency at its `yield`. A bare `except Exception:` that neither re-raises nor raises something else marks it handled, the same as in plain Python, so FastAPI's exception handlers never see it. The endpoint produced no response, so in FastAPI 0.143 the request wrapper raises `FastAPIError("Response not awaited. ...")` for the default request scope, and the server answers 500. Two things are lost: the original traceback, since the logged error does not chain to it, and the intended status, since a swallowed `HTTPException(404)` also becomes a 500. With `scope="function"` the 500 is an unrelated internal error instead. The fix is a bare `raise` after the rollback or logging step, raising an `HTTPException` that translates the error, or narrowing the `except` to the errors you mean to handle.
code
python · 29 linesimport logging
import tempfile
from pathlib import Path
from typing import Annotated
from fastapi import Depends, FastAPI
logger = logging.getLogger("renders")
app = FastAPI()
class RenderError(Exception):
pass
def get_workdir():
tmp = tempfile.TemporaryDirectory()
try:
yield Path(tmp.name)
except RenderError:
logger.warning("render failed, discarding %s", tmp.name)
raise # without this line the original error is lost
finally:
tmp.cleanup()
@app.post("/renders")
def create_render(workdir: Annotated[Path, Depends(get_workdir)]):
raise RenderError("template engine crashed")go deeper
Remember the rule from the docs: if you catch an exception in a yield dependency, end the except block with raise unless you raise a different exception.
Explain that the endpoint's exception is thrown in at the yield, that catching it marks it handled, and that FastAPI then has no response to send.
Diagnose from the symptom: bare 500s, a FastAPIError about a response not awaited, and HTTPExceptions that no longer reach clients. Fix it by narrowing or re-raising.
Make re-raise-or-translate a lint or review rule for yield dependencies, since this bug hides the evidence needed to debug it.
## How the endpoint's exception reaches the dependency A **yield dependency** is entered on an exit stack before the endpoint runs. When the endpoint raises, the exception unwinds through that stack, and FastAPI throws it **into the generator at the `yield` line**. From there it behaves like any exception raised by that line: - with no `try`, it propagates and the code after the `yield` is skipped; - with `try`/`finally`, the `finally` runs and the exception keeps propagating; - with `try`/`except` that matches it, the `except` block runs, and **if it ends without raising, the exception is gone**. This includes `HTTPException`. A 404 raised by the endpoint passes through every yield dependency on its way to FastAPI's exception handlers. ## What FastAPI does with a swallowed exception FastAPI's request wrapper runs the endpoint inside its exit stacks, then awaits the response it produced. If a dependency swallows the exception, the stacks close normally but there is **no response** to send. FastAPI 0.143 checks for that: | Dependency scope | What the server raises | Client sees | |---|---|---| | default `scope="request"` | `FastAPIError("Response not awaited. There's a high chance that the application code is raising an exception and a dependency with yield has a block with a bare except, or a block with except Exception, and is not raising the exception again. ...")` | 500 | | `scope="function"` | an internal error from the wrapper, unrelated to your code | 500 | The error that reaches the log has no `__context__` or `__cause__` pointing at the swallowed exception, so the traceback that would explain the failure is never written. The message names the likely culprit, which makes it the string to search for when a FastAPI service starts returning bare 500s after a refactor. ## Why the status code is wrong too A swallowed `HTTPException` is lost like any other exception. An endpoint that raises `HTTPException(status_code=404, detail="Item not found")` behind a dependency with `except Exception: pass` answers **500 Internal Server Error**, because the 404 never reaches the handler that would have turned it into a JSON error body. Clients see a server fault where the API promised a not-found. ## The three correct shapes 1. **Re-raise the original.** Do the side work, then a bare `raise`: ```python try: yield workdir except RenderError: logger.warning("render failed, discarding %s", workdir) raise finally: cleanup() ``` 2. **Translate it.** Raise a new exception, typically `HTTPException(status_code=400, detail=...)`, from the `except` block. FastAPI handles the new one as usual; this works in both scopes because no response exists yet. 3. **Do not catch what you do not handle.** Prefer `except RenderError:` over `except Exception:`, and use `finally` for steps that must run on every path. A dependency that only needs cleanup needs no `except` at all. ## Common sources of the bug - an `except Exception:` added to roll back a transaction or discard a temporary directory, with the `raise` forgotten; - a logging helper that "records and continues", copied from a background worker where continuing was correct; - `contextlib.suppress(...)` wrapped around the `yield`, which has the same effect as an `except` that does not raise. ## Catching it before production The bug only shows on the failure path, which happy-path tests never take. A few habits find it early: - write at least one test per route that forces the endpoint to raise, and assert the status code the API promises; - run those tests with `fastapi.testclient.TestClient` at its default `raise_server_exceptions=True`, where the swallowed case surfaces as `FastAPIError` instead of the expected exception; - in review, read every `except` in a yield dependency and check that it ends in `raise` or raises something new; - prefer `finally` for cleanup, so an `except` appears only where there is real handling to do. The safe mental model is that a yield dependency is a bystander to the endpoint's errors: it may observe them, clean up after them or translate them, but it must never make them disappear. ## Release history Before FastAPI 0.110, an exception caught and not re-raised in a yield dependency was still forwarded to the exception handlers. 0.110 stopped that, to fix memory growth from forwarded exceptions and to match plain Python. Material written before that change describes the old forwarding behaviour; on 0.143 the swallowed exception is simply gone.
- If the endpoint raises HTTPException(404) and a yield dependency catches Exception, logs, then re-raises, what does the client get?The 404 with its JSON detail. `HTTPException` is an `Exception`, so the dependency's `except` block runs, but the bare `raise` sends the same exception on to FastAPI's handler. Be aware the block also runs for expected client errors, so a rollback or error log placed there fires on every 404 too.
- How would you find this bug in a running service that suddenly returns bare 500s?Search the logs for `FastAPIError` with the text "Response not awaited". Its message names the pattern: a yield dependency with a bare or `except Exception` block that does not raise again. Then audit the yield dependencies on the failing routes for an `except` that ends without `raise`, including `contextlib.suppress` around the `yield`.
- FastAPI still forwards an exception that a yield dependency caught and did not re-raise.
- A swallowed HTTPException(404) still reaches the client as a 404.
- The server log will show the original exception's traceback anyway.
- Catching Exception around the yield is harmless if the except block only logs.
- Re-raising from a yield dependency's except prevents its finally block from running.
Assumes FastAPI 0.143; before 0.110 FastAPI still forwarded an exception that a yield dependency caught and did not re-raise.