fastapi: Unable to catch `Exception` via exception_handlers since FastAPI 0.70.0
First Check
- I added a very descriptive title to this issue.
- I used the GitHub search to find a similar issue and didn’t find it.
- I searched the FastAPI documentation, with the integrated search.
- I already searched in Google “How to X in FastAPI” and didn’t find any information.
- I already read and followed all the tutorial in the docs and didn’t find an answer.
- I already checked if it is not related to FastAPI but to Pydantic.
- I already checked if it is not related to FastAPI but to Swagger UI.
- I already checked if it is not related to FastAPI but to ReDoc.
Commit to Help
- I commit to help with one of those options 👆
Example Code
################################################
#
# Pay attention: below is Python 3.10 syntax
#
################################################
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from pydantic import ValidationError
async def internal_server_error(request: Request, exc: Exception | ValidationError) -> "JSONResponse":
return JSONResponse(content={"detail": "Internal Server Error"}, status_code=500)
app = FastAPI(
exception_handlers={
Exception: internal_server_error,
ValidationError: internal_server_error,
},
)
@app.get("/call_me")
async def raise_exception() -> None:
raise Exception("I am exception.")
Description
- Open the browser and call the endpoint:
/call_me - It returns plain text:
Internal Server Error - But I excepted it return JSON:
{"detail": "Internal Server Error"}
Operating System
Linux
Operating System Details
No response
FastAPI Version
0.70.0
Python Version
Python 3.10.0
Additional Context
It works fine on FastAPI 0.68.2. Issue is also affected 0.69.0
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Reactions: 4
- Comments: 16 (3 by maintainers)
Same use case here, wanting to always return JSON even with generic exception. It seems to because of new starlette version https://github.com/encode/starlette/issues/1175.
I’m eagerly looking forward to https://github.com/tiangolo/fastapi/pull/4145 getting merged. 😄
Fixed by https://github.com/encode/starlette/pull/1262.
Same here. Pinning starlette to the version 0.14.2 fixed the issue.
Using 0.78, I cannot reproduce. I see a JSON response in my browser using the code in OP.
@Kludex did you validate against the just-released FastAPI 0.71.0 and confirm this is still an issue?
Same here. I noticed that when I set up Github actions and I haven’t listed fastapi version in the requirements file (which locally was 0.65.0) and on the CI it was 0.70.0). I am using httpx AsyncClient for my tests and I also have tests where I mock exceptions (pure Python exceptions) so my CI started to fail.