Customizing Error Handling in FastAPI
Question:
When sending an invalid JSON request to a FastAPI backend, an error is thrown with an unprocessable entity status code (422). The response includes verbose error details that are not ideal for user-friendly error handling. Is there a way to customize the error response?
Answer:
To handle this situation and customize the error response, you can override the request validation exception handler in FastAPI. Here's how to implement it:
Firstly, remember that you are passing an invalid JSON, and hence, the server correctly responds with the 422 Unprocessable Entity error.
Overriding the Exception Handler:
<code class="python">@app.exception_handler(RequestValidationError) async def validation_exception_handler(request: Request, exc: RequestValidationError): return JSONResponse( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, content=jsonable_encoder({ "detail": exc.errors(), # optionally include the errors "body": exc.body, "custom msg": {"Your error message"} }), )</code>
Returning a PlainTextResponse:
Alternatively, you can also return a custom error message using a PlainTextResponse:
<code class="python">@app.exception_handler(RequestValidationError) async def validation_exception_handler(request, exc): return PlainTextResponse(str(exc), status_code=422)</code>
The above is the detailed content of How to Customize Error Responses for Invalid JSON Requests in FastAPI?. For more information, please follow other related articles on the PHP Chinese website!