Home  >  Article  >  Backend Development  >  How to Customize Error Responses for FastAPI

How to Customize Error Responses for FastAPI

Susan Sarandon
Susan SarandonOriginal
2024-10-21 06:25:30627browse

How to Customize Error Responses for FastAPI

Customization of Error Responses in FastAPI

In FastAPI, when invalid requests are encountered, it typically responds with a 422 Unprocessable Entity error. This response may not always align with the desired user experience. Here's how to customize the error response to suit your application's specific requirements.

The default error response includes details such as "Extra data" and "Actual" data. To tailor this response, FastAPI provides the ability to override the request validation exception handler. As demonstrated in the code example below, you can define a custom handler:

<code class="python">from fastapi import FastAPI, Body, Request, status
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import BaseModel

app = FastAPI()

@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>

Alternatively, you can return a PlainTextResponse with a custom error message:

<code class="python">from fastapi.responses import PlainTextResponse

@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
    return PlainTextResponse(str(exc), status_code=422) </code>

These customization options allow you to handle error responses gracefully and provide a user-friendly experience even when encountering invalid requests.

The above is the detailed content of How to Customize Error Responses for FastAPI. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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