pythonexceptionfastapi

How to handle exceptions for all the sub apps in FastAPI


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?


Solution

  • So I found out that I need to add all the sub apps to the exception handler function and it fixed my problem:

    def exception_handler(app: FastAPI):
        @app.exception_handler(CustomException)
        async def custom_exception_handler(request: Request, exception: CustomException) -> JSONResponse:
            return JSONResponse(
                status_code=exception.status_code, content={"error": exception.message}
            )
    

    After defining the above function, main app and all the sub apps need to be sent to it:

    exception_handler(app)
    exception_handler(subapp1)