Python / FastAPI Basics Interview Questions
How do you create custom exception handlers in FastAPI?
Use @app.exception_handler(ExceptionClass) to catch specific exception types globally and return custom JSON responses. This is cleaner than wrapping every route in try/except.
from fastapi import FastAPI, Request from fastapi.responses import JSONResponse from fastapi.exceptions import RequestValidationError from starlette.exceptions import HTTPException as StarletteHTTPException app = FastAPI() # Custom exception class class ItemNotFoundError(Exception): def __init__(self, item_id: int): self.item_id = item_id # Handler for our custom exception @app.exception_handler(ItemNotFoundError) async def item_not_found_handler(request: Request, exc: ItemNotFoundError): return JSONResponse( status_code=404, content={"error": "not_found", "item_id": exc.item_id}, ) # Override the default validation error handler @app.exception_handler(RequestValidationError) async def validation_exception_handler(request: Request, exc: RequestValidationError): return JSONResponse( status_code=422, content={ "error": "validation_failed", "detail": exc.errors(), "body": exc.body, }, ) # Override generic HTTP exception handler @app.exception_handler(StarletteHTTPException) async def http_exception_handler(request: Request, exc: StarletteHTTPException): return JSONResponse( status_code=exc.status_code, content={"error": "http_error", "detail": exc.detail}, ) @app.get("/items/{item_id}") def get_item(item_id: int): if item_id == 999: raise ItemNotFoundError(item_id=item_id) # triggers custom handler return {"item_id": item_id}
More Related questions...