-
First Check
Commit to Help
Example Codeimport logging
from typing import Annotated, AsyncGenerator
from anyio import open_file
from fastapi import Depends, FastAPI
async def get_thingy() -> AsyncGenerator[str, None]:
"""Should return a thingy, but is a badly behaved dependency, does nothing"""
try:
async with await open_file("/path/to/aintnosuchfileyo.txt", "r") as f:
yield await f.read()
except Exception:
logging.warning("Ain't no such file yo!")
app = FastAPI()
@app.get("/")
async def root(thingy: Annotated[str, Depends(get_thingy)]):
return {"message": f"Hello {thingy}"} DescriptionWhen running a FastAPI app whose endpoints use a number of dependencies (including a python-oracledb async connection pool), the following error occasionally occurs (redacted stack trace copied from production logs):
This is caused by python-oracledb failing to get a connection from its pool. Not sure if this is related to the Python core issue Worse error from asynccontextmanager in Python 3.10, which, from a quick Google search, was the only relevant discussion that I could find. Would be great if FastAPI could catch that Operating SystemLinux Operating System DetailsNo response FastAPI Version0.115.6 Pydantic Version2.10.3 Python Version3.11.4 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments
-
I managed to put together some example code that reliably reproduces this error, I've updated "example code" above. |
Beta Was this translation helpful? Give feedback.
-
Hello @Jaza, about the traceback and your error, this is because the generator is no yielding anything due the exception occurring. You are no able to see what exception is because your generator does not re-raise the error. Please read Dependencies with yield and except. Hope this helps. |
Beta Was this translation helpful? Give feedback.
-
This is in
(If you were actually making logs, then you should be able to find the actual (the sensible ones!) error messages in the logs 😀 ) |
Beta Was this translation helpful? Give feedback.
-
@luzzodev yes, thanks, I found the section in the docs that you pointed out, and I've fixed my custom dependency to re-raise the exception as it should. And @alv2017 yes, I can indeed also see the warning that I'm logging (where I should have been re-raising an exception), in my logs. So, yes, this was a bug in my code, and it's a gotcha that's already covered in the FastAPI docs. But, nevertheless, I feel that there's room for improvement here on the FastAPI side: FastAPI can and should re-raise |
Beta Was this translation helpful? Give feedback.
Hello @Jaza,
about the traceback and your error, this is because the generator is no yielding anything due the exception occurring. You are no able to see what exception is because your generator does not re-raise the error.
Please read Dependencies with yield and except.
Hope this helps.