[Python] How to force all exceptions to go through a FastAPI middleware?

Discussão em 'Python' iniciado por Stack, Março 18, 2025.

  1. Stack

    Stack Membro Participativo

    I am writing an app using FastAPI. Parts of my code raise different exceptions, which I need to process. I want all that processing to be done in a single place (with different except blocks depending on what exception was raised). I tried to do this by adding the following (simplified) middleware to my FastAPI app:

    from fastapi import APIRouter, FastAPI, Request, HTTPException, Response, status
    from starlette.middleware.base import BaseHTTPMiddleware
    from fastapi.responses import JSONResponse

    class ExceptionHandlerMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
    try:
    return await call_next(request)
    except HTTPException as e:
    return JSONResponse(status_code=e.status_code, content={'message': e.detail})
    except Exception as e:
    return JSONResponse(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, content={'message': str(e)})

    # app creation and config go here....

    app.add_middleware(ExceptionHandlerMiddleware)


    The problem is that this does not work for some specific exceptions, which FastAPI handles by default (for example, if an HTTPException is raised, it will never reach the except block in my middleware, because it will already be processed by default, before reaching the middleware).

    FastAPI's documentation provides a way to override the default behavior for specific exceptions, but this is tedious and not scalable. Is there a way to globally force all exception handling to go through my middleware? (bonus points if anyone knows a way to do this without using decorators, as one requirement I have is to not use them).

    Continue reading...

Compartilhe esta Página