How do you handle custom exceptions in FastAPI?medium

Type
conceptual
Topic
exceptions
Frequency
common
Tags
FastAPI, exceptions, HTTPException, error handling, JSONResponse
Answer

Raise HTTPException anywhere in a route or dependency to immediately return an error response. For domain-specific errors, define custom exception classes and register handlers with @app.exception_handler to convert them to HTTP responses.

Explanation

This separation keeps route code clean: routes raise domain exceptions (DocumentNotFoundError), handlers translate them to HTTP responses (404 JSON). Override FastAPI's default RequestValidationError handler to customise the 422 response envelope for consistency across all error formats. Return JSONResponse from handlers for full control over status code and body. The pattern mirrors Python's own exception hierarchy — catch at different granularities by targeting base or specific exception classes.

Follow-upHow would you define a RateLimitExceeded exception that returns 429 with a retry_after field?
Follow-upHow do you override the default 422 validation error response format?
Follow-upWhat is the difference between raising HTTPException and registering a custom exception handler?