📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials FastAPI FastAPI Advanced Error Handling

FastAPI Advanced Error Handling

5 min read
Custom exception classes and global handlers for consistent structured JSON error responses.

Advanced Error Handling in FastAPI

from fastapi import Request
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError

class NotFoundError(Exception):
    def __init__(self, resource: str, id: int):
        self.message = resource + " #" + str(id) + " not found"
        self.code    = 404

class AuthError(Exception):
    def __init__(self, reason: str = "Unauthorized"):
        self.message = reason
        self.code    = 401

@app.exception_handler(NotFoundError)
async def not_found_handler(request: Request, exc: NotFoundError):
    return JSONResponse(status_code=exc.code,
                        content={"detail": exc.message})

@app.exception_handler(AuthError)
async def auth_handler(request: Request, exc: AuthError):
    return JSONResponse(status_code=exc.code,
        content={"detail": exc.message},
        headers={"WWW-Authenticate": "Bearer"})

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

# Usage
raise NotFoundError("Post", 42)
raise AuthError("Token expired")