Error handling and HTTPException

Difficulty: Beginner

Question

How does FastAPI handle errors? How do you raise and customize HTTP errors?

Answer

FastAPI uses `HTTPException` to raise HTTP errors. Raise it anywhere in a path operation or dependency and FastAPI returns a JSON response with the given status code and detail.

For global error handling, use `@app.exception_handler(ExceptionType)` to register custom handlers for specific exception types, including Pydantic's `RequestValidationError` for 422 errors.

FastAPI also has a built-in handler for `RequestValidationError` (422) and `HTTPException` (any 4xx/5xx). You can override these.

Code examples

HTTPException and custom exception handler

from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError

app = FastAPI()

class ItemNotFound(Exception):
    def __init__(self, item_id: int):
        self.item_id = item_id

@app.exception_handler(ItemNotFound)
async def item_not_found_handler(request: Request, exc: ItemNotFound):
    return JSONResponse(
        status_code=404,
        content={"error": f"Item {exc.item_id} not found"}
    )

@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
    return JSONResponse(
        status_code=422,
        content={"detail": exc.errors(), "body": str(exc.body)}
    )

@app.get("/items/{item_id}")
def get_item(item_id: int):
    if item_id not in [1, 2, 3]:
        raise ItemNotFound(item_id=item_id)  # custom exception
    if item_id < 0:
        raise HTTPException(status_code=400, detail="ID must be positive")
    return {"item_id": item_id}

Key points

Concepts covered

HTTPException, exception handlers, status codes, custom errors