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}
)
If you want to use custom error message instead of Uvicorn's error message, you can use middle ware.
So in this case, you can create a custom middleware that catches requests resulting in a 503
error and responds with a custom message.
Here is a code.
class ServiceUnavailableMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
response = await call_next(request)
if response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE:
return JSONResponse(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
content={"message": "Service is temporarily unavailable. Please try again later."}
)
return response
app = FastAPI()
app.add_middleware(ServiceUnavailableMiddleware)
I think this middleware intercepts the responses with a 503
status code and modifies them in custom message.