{"record":{"id":"054b6a3a7e4f2c4d","repo":"tiangolo/fastapi","slug":"response-not-awaited-there-s-a-high-chance-that-t","errorCode":null,"errorMessage":"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. Read more about it in the docs: https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#dependencies-with-yield-and-except","messagePattern":"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\\. Read more about it in the docs: https://fastapi\\.tiangolo\\.com/tutorial/dependencies/dependencies-with-yield/#dependencies-with-yield-and-except","errorType":"exception","errorClass":"FastAPIError","httpStatus":null,"severity":"critical","filePath":"fastapi/routing.py","lineNumber":149,"sourceCode":"        else functools.partial(run_in_threadpool, func)  # type: ignore[call-arg]\n    )  # ty: ignore[invalid-assignment]\n\n    async def app(scope: Scope, receive: Receive, send: Send) -> None:\n        request = Request(scope, receive, send)\n\n        async def app(scope: Scope, receive: Receive, send: Send) -> None:\n            # Starts customization\n            response_awaited = False\n            async with AsyncExitStack() as request_stack:\n                scope[\"fastapi_inner_astack\"] = request_stack\n                async with AsyncExitStack() as function_stack:\n                    scope[\"fastapi_function_astack\"] = function_stack\n                    response = await f(request)\n                await response(scope, receive, send)\n                # Continues customization\n                response_awaited = True\n            if not response_awaited:\n                raise FastAPIError(\n                    \"Response not awaited. There's a high chance that the \"\n                    \"application code is raising an exception and a dependency with yield \"\n                    \"has a block with a bare except, or a block with except Exception, \"\n                    \"and is not raising the exception again. Read more about it in the \"\n                    \"docs: https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#dependencies-with-yield-and-except\"\n                )\n\n        # Same as in Starlette\n        await wrap_app_handling_exceptions(app, request)(scope, receive, send)\n\n    return app\n\n\n# Copy of starlette.routing.websocket_session modified to include the\n# dependencies' AsyncExitStack\ndef websocket_session(\n    func: Callable[[WebSocket], Awaitable[None]],\n) -> ASGIApp:","sourceCodeStart":131,"sourceCodeEnd":167,"githubUrl":"https://github.com/tiangolo/fastapi/blob/3e8d1526d83a90aaf7d6eb6dc682bf150f180b25/fastapi/routing.py#L131-L167","documentation":"FastAPIError (RuntimeError) raised in request_response's inner app (routing.py:149). The handler sets response_awaited = False, awaits the endpoint inside an AsyncExitStack, then sets response_awaited = True only after `await response(scope, receive, send)` runs. If a yielding dependency catches the endpoint's exception with a bare `except:` or `except Exception:` and does not re-raise, the exception is swallowed, the response is never sent, response_awaited stays False, and FastAPI raises this error to signal that the response was silently lost.","triggerScenarios":"A dependency defined with `yield` wraps its yield in try/except that catches the exception raised by the endpoint (bare except or except Exception) and does not re-raise it. The dependency's teardown runs, swallows the error, and the response coroutine never executes.","commonSituations":"Adding try/except around `yield` in a DB-session or resource dependency to 'log and continue'; catching Exception to suppress errors; upgrading an app where a dependency silently absorbed errors that FastAPI now detects.","solutions":["Re-raise in the except block of the yielding dependency: `except Exception: ...; raise`.","Avoid bare `except:` / `except Exception:` around the yield; only handle specific exceptions you intend to suppress.","Log inside the except but always re-raise so FastAPI can produce the error response.","Reproduce with the app in question and check every dependency-with-yield for a swallowing except block."],"exampleFix":"// before\ndef get_session():\n    session = Session(engine)\n    try:\n        yield session\n    except Exception:\n        pass  # swallows the endpoint error -> FastAPIError: Response not awaited\n    finally:\n        session.close()\n\n// after\ndef get_session():\n    session = Session(engine)\n    try:\n        yield session\n    except Exception:\n        logger.exception(\"request failed\")\n        raise  # let FastAPI handle the error response\n    finally:\n        session.close()","handlingStrategy":"try-catch","validationCode":"# Static check: flag yielding dependencies that swallow exceptions\nimport ast, pathlib\n\nclass YieldExceptChecker(ast.NodeVisitor):\n    def __init__(self, path):\n        self.path = path; self.issues = []\n    def visit_FunctionDef(self, node):\n        has_yield = any(isinstance(n, ast.Yield) for n in ast.walk(node))\n        if has_yield:\n            for n in ast.walk(node):\n                if isinstance(n, ast.ExceptHandler):\n                    t = n.type\n                    bare = t is None\n                    broad = isinstance(t, ast.Name) and t.id == \"Exception\"\n                    has_raise = any(isinstance(c, ast.Raise) for c in ast.walk(n))\n                    if (bare or broad) and not has_raise:\n                        self.issues.append((self.path, n.lineno))\n        self.generic_visit(node)\n\nfor p in pathlib.Path('.').rglob('*.py'):\n    YieldExceptChecker(str(p)).visit(ast.parse(p.read_text()))","typeGuard":null,"tryCatchPattern":"# In the yielding dependency itself\nimport logging\nlog = logging.getLogger(__name__)\n\ndef get_db():\n    db = Session()\n    try:\n        yield db\n    except Exception:\n        log.exception(\"error during request\")\n        raise  # MUST re-raise so FastAPI can build the error response\n    finally:\n        db.close()","preventionTips":["Always re-raise inside except blocks of a yielding dependency.","Never use bare `except:` or `except Exception:` without `raise` around a yield.","Catch only the specific exceptions you intend to suppress.","Add an integration test that forces an endpoint error to confirm a real 5xx comes back."],"tags":["dependencies-with-yield","exception-handling","routing","response","fastapi"],"backgroundTag":null,"analyzedSha":"3e8d1526d83a90aaf7d6eb6dc682bf150f180b25","analyzedAt":"2026-08-11T02:34:52.986Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}