Raise HTTPException and register exception handlers for consistent JSON error responses.
Exception Handling
from fastapi import HTTPException, Request
from fastapi.responses import JSONResponse
from fastapi.exception_handlers import http_exception_handler
# Raise HTTP errors
raise HTTPException(status_code=404, detail="User not found")
raise HTTPException(status_code=422, detail=[{"field": "email", "msg": "Invalid"}])
# Custom exception class
class AppError(Exception):
def __init__(self, message: str, code: int = 400):
self.message = message
self.code = code
# Register exception handler
@app.exception_handler(AppError)
async def app_error_handler(request: Request, exc: AppError):
return JSONResponse(status_code=exc.code, content={"detail": exc.message})
@app.exception_handler(404)
async def not_found_handler(request: Request, exc: HTTPException):
return JSONResponse(status_code=404, content={"detail": "Not found", "path": str(request.url)})
# Validation error response customization
from fastapi.exceptions import RequestValidationError
@app.exception_handler(RequestValidationError)
async def validation_handler(request: Request, exc: RequestValidationError):
return JSONResponse(status_code=422, content={"errors": exc.errors()})