[Python] How to make a custom error message for Service Unavailable in FastAPI?

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

  1. Stack

    Stack Membro Participativo

    I'm running my app like so:

    uvicorn main:app --host 0.0.0.0 --port 8080 --workers 2 --limit-concurrency 10


    Versions are:

    fastapi==0.103.2
    uvicorn==0.34.3


    When I start slamming it, I get the expected 503 Service Unavailable error.

    I want to have a custom error message when this happens.

    I thought this code would catch this error, but that code never gets touched when I get a 503.

    What am I doing wrong?

    app = FastAPI()


    class ServiceUnavailableException(Exception):
    def __init__(self, message: str):
    self.message = message


    @app.exception_handler(ServiceUnavailableException)
    async def service_unavailable_exception_handler(request: Request, exc: ServiceUnavailableException):
    return JSONResponse(
    status_code=status.HTTP_503_SERVICE_UNAVAILABLE, # Use 503 status code
    content={"message": exc.message}
    )

    Continue reading...

Compartilhe esta Página