Under The Hood
backend fastapi FastAPI 0.100+

Custom RequestValidationError & HTTP Status Code Mapping

Last updated
Prerequisites:
FastAPI HTTP exceptions
Pydantic ValidationError structure
  • fastapi
  • exception-handlers
  • validation-error
  • http-exception
  • error-handling

Read at your depth

The practical view

You register custom exception handlers in FastAPI using `@app.exception_handler(ExceptionClass)`. To customize default 422 validation errors, override `RequestValidationError`: `@app.exception_handler(RequestValidationError) async def validation_handler(request: Request, exc: RequestValidationError): return JSONResponse(status_code=400, content={'errors': ...})`. You can also create custom business domain exceptions.

The same idea in other frameworks

fastapi equivalent
`@app.exception_handler(CustomError)` returning `JSONResponse`.

Legacy vs modern

Default Verbose 422 Error vs Clean Standardized Error Envelope

Default FastAPI 422 errors expose internal schema details; custom exception handlers standardize error envelopes.

before → after
Default Verbose 422 Error Response
// Default FastAPI validation response exposes raw Pydantic detail lists
Standardized Custom Exception Handler
@app.exception_handler(RequestValidationError) async def handler(req, exc): ... // ✅ NEW

Interview gotchas

Context

Interviewers test your knowledge of FastAPI vs Starlette exception inheritance.

The mechanical answer

`fastapi.HTTPException` inherits from `starlette.exceptions.HTTPException`. The difference is that `fastapi.HTTPException` accepts a `headers` parameter and allows passing any JSON-serializable structure to `detail` (dict, list, string), whereas Starlette's only accepts strings. Always import and raise `fastapi.HTTPException` in FastAPI applications.

Trap

If you register an exception handler specifically for `starlette.exceptions.HTTPException`, it will catch `fastapi.HTTPException` too, but accessing `exc.headers` may require `getattr`.

Under The Hood — a multi-depth technical interview hub.

Third-party licenses Press ⌘ K to search.