Throw HttpExceptions so they can be caught by middleware? #9103
-
Exampleimport uvicorn
from fastapi import FastAPI
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
from starlette.requests import Request
from starlette.responses import Response, JSONResponse
from fastapi.exceptions import HTTPException
class RequestHandlingMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
try:
return await call_next(request)
except Exception as ex:
# logging/metrics
return JSONResponse({"detail": repr(ex), "other_stuff": "blah"})
app = FastAPI()
app.add_middleware(RequestHandlingMiddleware)
@app.get("/exception")
def throw_exception(http_exception: bool = True, message: str = "Test message"):
if http_exception:
raise HTTPException(status_code=500, detail=message)
raise Exception(message)
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=5000, debug=True)Description
From here it looks HTTPExceptions are special and require using a dedicated exception handler to override how they are handled. Can this be clarified in the documentation? Are there any plans to add the throw these exceptions so that something like a middleware could catch and log all exceptions raised while processing the request? IMO this would be easier than having to decorate route handlers with exception decorators. Environment
|
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
|
A little late to the party, but I accomplished this by inspecting the response object returned by |
Beta Was this translation helpful? Give feedback.
-
|
I'm not sure if this is explained in FastAPI's docs, but it is in Starlette's: https://www.starlette.io/exceptions/#errors-and-handled-exceptions
I'm also using the solution mentioned by @TheBeege. |
Beta Was this translation helpful? Give feedback.
-
|
really really late to this party, but i found this solution out there |
Beta Was this translation helpful? Give feedback.
I'm not sure if this is explained in FastAPI's docs, but it is in Starlette's: https://www.starlette.io/exceptions/#errors-and-handled-exceptions
HTTPExceptionis considered a handled error by default, so it won't fall into anexceptblock in outer middlewares.I'm also using the solution mentioned by @TheBeege.