In FastAPI, how do you override the RequestValidationError handler to return your own error envelope without hiding what the client got wrong?
answer
- same decorator, built-in exception class
- exc.errors() is the list
- keep loc, msg and type
- exc.body and str(exc) leak
- reuse the default handler
basics
~10 sRegister @app.exception_handler(RequestValidationError), map exc.errors() into your envelope keeping each loc, msg and type, and return a JSONResponse with 422. Never return str(exc) or echo exc.body, which carry endpoint details and possibly sensitive request data.
solid answer
~40 sYou decorate an async function taking `(request, exc)` with `@app.exception_handler(RequestValidationError)`, which replaces FastAPI's default. Inside, `exc.errors()` returns the list of Pydantic error dicts; map each to your envelope but keep `loc`, `msg` and `type`, because those are what tell the client which field to fix, and keep status 422 so clients and the generated docs still agree. Run values through `jsonable_encoder` or pick only string fields, since `ctx` can hold an exception object that `JSONResponse` cannot serialize. Don't return `str(exc)`, which includes the endpoint's file and line, and treat `exc.body` as log material, not response content. If you only want to log, call `fastapi.exception_handlers.request_validation_exception_handler(request, exc)` and return its response.
code
python · 32 linesimport logging
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
logger = logging.getLogger("payments")
app = FastAPI()
class TransferIn(BaseModel):
amount: int = Field(gt=0)
currency: str = Field(min_length=3, max_length=3)
@app.exception_handler(RequestValidationError)
async def validation_envelope(request: Request, exc: RequestValidationError):
fields = [
{"loc": list(err["loc"]), "msg": err["msg"], "type": err["type"]}
for err in exc.errors()
]
logger.info("rejected %s: %d field errors", request.url.path, len(fields))
return JSONResponse(
status_code=422,
content={"error": {"code": "VALIDATION_FAILED", "fields": fields}},
)
@app.post("/transfers")
async def create_transfer(transfer: TransferIn):
return {"status": "accepted"}go deeper
Recall that RequestValidationError is the exception behind the 422 and that @app.exception_handler can replace its handler.
Explain errors() versus body, why loc, msg and type must survive the envelope, and how to delegate to request_validation_exception_handler.
Spot the production traps: ctx exception objects breaking serialization, file and line leaking through str(exc), sensitive input echoed back, docs drifting from the real status.
Decide which validation details are part of the public contract, and make the handler, the documented schema and client expectations change together.
## Replacing the default handler FastAPI installs a handler for `fastapi.exceptions.RequestValidationError` when the app is created, using `setdefault`, so any handler you register for the same class wins. There are three equivalent ways to register it: 1. the decorator `@app.exception_handler(RequestValidationError)`; 2. `app.add_exception_handler(RequestValidationError, handler)`; 3. the constructor argument `FastAPI(exception_handlers={RequestValidationError: handler})`. The handler receives the Starlette `Request` and the exception, and it must **return a response object**, typically a `JSONResponse`. An `async def` handler runs on the event loop; a plain `def` handler is run in the thread pool. WebSocket routes raise a separate class, `WebSocketRequestValidationError`, with its own default handler that closes the socket; overriding the HTTP one does not touch it. ## What the exception gives you | Attribute | What it holds | Use it for | |---|---|---| | `exc.errors()` | the list of Pydantic 2 error dicts (`type`, `loc`, `msg`, `input`, `ctx`) | building the client response | | `exc.body` | the parsed body, or the raw text when JSON decoding failed | logging while debugging | | `str(exc)` | a summary with every error plus the endpoint's file, line and function | server logs only | ## Keeping what the client got wrong The point of a 422 is to tell the caller **which field** failed and **why**. A good envelope keeps three things from every item: - **`loc`**, the path to the value, beginning with its source (`body`, `query`, `path`, `header`, `cookie`); - **`type`**, the stable code a client program can branch on (`missing`, `greater_than`, `json_invalid`); - **`msg`**, a readable explanation for a developer looking at the response. A handler that collapses everything into `"Invalid request"` makes the API harder to use without making it safer: the client already knows what it sent. The other decision is the **status code**. FastAPI's own docs show a handler answering 400, which is allowed, but the generated OpenAPI schema keeps documenting a 422 with FastAPI's default body unless you also declare your own 422 response. Keeping 422 avoids one of those two mismatches. ## What not to send back - **`str(exc)`**. Since the exception carries endpoint context, its string form names the source file, line number and function of the path operation. The docs warn about exactly this; it belongs in logs. - **`exc.body`**. The docs show echoing the body back, which is convenient while developing. In a payments API the body may contain a card number or a token, and echoing it puts that value into every proxy, client log and error tracker that records responses. - **Raw `ctx` values.** A custom Pydantic validator that raises `ValueError` leaves that exception object in the item's `ctx`. `JSONResponse(content={"detail": exc.errors()})` then fails with `TypeError: Object of type ValueError is not JSON serializable`, turning a 422 into a 500. Either pass the list through `fastapi.encoders.jsonable_encoder`, as the default handler does, or copy only `loc`, `msg` and `type`. The `input` key deserves the same thought: it echoes the submitted value. Keeping it is often fine for a username; dropping it is safer for card or secret fields. ## Reusing the default When you only need a side effect, such as a metric or a log line, you do not have to rebuild the body. `fastapi.exception_handlers` exposes the defaults, so the handler can log and then `return await request_validation_exception_handler(request, exc)`. Raising the exception again from inside the handler does **not** fall back to the default: the exception escapes to Starlette's server-error middleware and the client gets a 500. ## Testing the override A few in-process tests with `fastapi.testclient.TestClient` pin the behaviour down: - a body with two bad fields, asserting status 422 and both `loc` paths in the envelope; - a body cut off mid-object, asserting the `json_invalid` item; - a value rejected by a custom validator, which is the case that exposes an unencoded `ctx`. ## Worked example In the payments API, the handler below keeps status 422, copies only `loc`, `msg` and `type` into a `VALIDATION_FAILED` envelope and logs the count. A transfer with `amount: 0` and `currency: "EURO"` receives two field errors, `greater_than` on `["body", "amount"]` and `string_too_long` on `["body", "currency"]`. A body cut off mid-object receives one `json_invalid` error whose `loc` is `"body"` plus the character offset where decoding failed, in the same envelope.
- In a FastAPI app, what is in exc.body when the request carried malformed JSON?The raw text the client sent, because decoding failed before any parsing. For a valid JSON body that failed model validation, `exc.body` holds the parsed value instead. Either way it is the client's own data, which is why it belongs in debug logs rather than in the response of an API that handles sensitive fields.
- Your FastAPI 422 handler returns 400 instead. What else still says 422?The generated OpenAPI schema. FastAPI adds a 422 response referencing `HTTPValidationError` to every operation with parameters or a body, whatever handler is installed, so the docs and generated clients describe a response the API no longer sends unless you declare your own error responses.
- How do you add logging to FastAPI's 422 handling without changing the response body?Register a handler for `RequestValidationError` that logs what you need, then `return await request_validation_exception_handler(request, exc)` imported from `fastapi.exception_handlers`. The client receives exactly the default `{"detail": [...]}` body.
- Returns str(exc) to the client as the error message
- Echoes exc.body back in a payments API response
- Replaces every field error with a single generic message
- Passes exc.errors() to JSONResponse without jsonable_encoder
- Re-raises the exception expecting FastAPI's default handler to run
- Assumes overriding the handler also changes the documented 422 schema