[Python] How to handle exceptions for all the sub apps in FastAPI

Discussão em 'Python' iniciado por Stack, Junho 27, 2025.

  1. Stack

    Stack Membro Participativo

    I have a FastAPI project containing multiple sub apps (The sample includes just one sub app).

    main_app = FastAPI()

    class CustomException(Exception):
    def __init__(self, message: str, status_code: int, name: str = "Exception"):
    Exception.__init__(self)
    self.name = name
    self.status_code = status_code
    self.message = message

    @main_app.exception_handler(CustomException)
    async def custom_exception_handler(exception: CustomException) -> JSONResponse:
    return JSONResponse(
    status_code=exception.status_code, content={"error": exception.message}
    )
    main_app.mount("/subapp", subapp1)


    I've handled the exceptions in main app, but not in subapp1. Now if I use the CustomException in subapp1:

    raise CustomException(
    status_code=status.HTTP_404_NOT_FOUND,
    message=f"{self.model.__name__} not found",
    )


    I get this error:


    RuntimeError: Caught handled exception, but response already started.
    ​

    It seems like when raising CustomException in a sub app, it won't be handled by the main app exception handler. So how can I handle the exceptions from all the sub app using the main app exception handler?

    Continue reading...

Compartilhe esta Página