FastAPI cannot catch exception with status code 500

38 views Asked by At

I'm using Fastapi "0.104.1". I'm able to catch every exception raised except for Internal Server Error 500. Here is my code: main.py

app = FastAPI(title='App')

app.add_exception_handler(400, exception_handler.exception_400_handler)
app.add_exception_handler(500, exception_handler.exception_500_handler)

exception_handler.py

async def exception_400_handler(request, exc):
    return JSONResponse(
        status_code=status.HTTP_400_BAD_REQUEST,
        content=jsonable_encoder({"error": {"message": exc.detail, "type": status.HTTP_400_BAD_REQUEST}}),
    )

async def exception_500_handler(request, exc):
    return JSONResponse(
        status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
        content=jsonable_encoder({"error": {"message": exc.detail, "type": status.HTTP_500_INTERNAL_SERVER_ERROR}}),
    )

As said before, I'm able to catch exception with status 400, but not with status 500. Example:

raise HTTPException(status_code=400, detail="Item not found") # enter in the exception_400_handler
raise HTTPException(status_code=500, detail="Error on update item") # NOT enter in the exception_500_handler

Thanks for any help

0

There are 0 answers