How to Customize Error Responses for Invalid JSON Requests in FastAPI?

Susan Sarandon
Release: 2024-10-21 06:28:30
Original
733 people have browsed it

How to Customize Error Responses for Invalid JSON Requests in FastAPI?

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:

  1. In your FastAPI application, add the following code to override the default exception handler for RequestValidationError:
<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>
Copy after login
  1. In the above code, you can customize the error message by modifying the value of "custom msg".

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>
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!