Global Exception handler triggers ASGI Exception #11738
-
First Check
Commit to Help
Example Codefrom fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
app = FastAPI(debug=False)
@app.exception_handler(Exception)
async def unhandled_exception_handler(request: Request, exc: Exception):
return JSONResponse(
status_code=400,
content={"message": str(exc)},
)
@app.get("/home")
def read_root():
a = 10 / 0
return {"hello": "world"} DescriptionWhen I call the endpoint "/home", it returns {"message": "division by zero"}. But it still triggers an exception in ASGI INFO: 127.0.0.1:53515 - "GET /home HTTP/1.1" 400 Bad Request Operating SystemWindows Operating System DetailsNo response FastAPI Versionlatest Pydantic Versionlatest Python Versionlatest Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
When you create an exception handler for All the exceptions inherited from You can read more in starlette docs: https://www.starlette.io/exceptions/ Looks like the same question: #11348 |
Beta Was this translation helpful? Give feedback.
When you create an exception handler for
Exception
it works in a different way.All the exceptions inherited from
HTTPException
are handled byExceptionMiddleware
, but all other exceptions (not inherited fromHTTPException
) go toServerErrorMiddleware
. AndServerErrorMiddleware
re-raises all these exceptions. As I know you can't change it.You can read more in starlette docs: https://www.starlette.io/exceptions/
Looks like the same question: #11348