Custom exception handlers let you control how your app responds when errors happen. This helps you give clear, friendly messages instead of confusing errors.
0
0
Custom exception handlers in FastAPI
Introduction
You want to show a special message when a user sends bad data.
You want to log errors and still send a neat response to users.
You want to handle specific errors differently, like 'not found' or 'unauthorized'.
You want to keep your app from crashing by catching unexpected errors.
You want to customize error responses for API clients.
Syntax
FastAPI
from fastapi import FastAPI, Request from fastapi.responses import JSONResponse from fastapi.exceptions import RequestValidationError from starlette.exceptions import HTTPException app = FastAPI() @app.exception_handler(ExceptionType) async def custom_exception_handler(request: Request, exc: ExceptionType): return JSONResponse( status_code=exc.status_code, content={"message": "Custom error message"} )
Replace ExceptionType with the error you want to handle, like HTTPException or your own error class.
The handler function must be async and accept request and exc parameters.
Examples
This handles all HTTP errors and sends a friendly message with the error detail.
FastAPI
from fastapi import HTTPException from fastapi.responses import JSONResponse @app.exception_handler(HTTPException) async def http_exception_handler(request: Request, exc: HTTPException): return JSONResponse( status_code=exc.status_code, content={"message": f"Oops! {exc.detail}"} )
This catches validation errors when user input is wrong and sends a clear message.
FastAPI
from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse @app.exception_handler(RequestValidationError) async def validation_exception_handler(request: Request, exc: RequestValidationError): return JSONResponse( status_code=422, content={"message": "Invalid input, please check your data."} )
This shows how to handle your own error type with a custom message.
FastAPI
from fastapi.responses import JSONResponse class MyCustomError(Exception): def __init__(self, name: str): self.name = name @app.exception_handler(MyCustomError) async def my_custom_error_handler(request: Request, exc: MyCustomError): return JSONResponse( status_code=400, content={"message": f"Error with {exc.name}!"} )
Sample Program
This app has a custom error for missing items. If you ask for an item not in the list, it sends a clear 404 message.
FastAPI
from fastapi import FastAPI, HTTPException, Request from fastapi.responses import JSONResponse app = FastAPI() class ItemNotFoundError(Exception): def __init__(self, item_id: int): self.item_id = item_id @app.exception_handler(ItemNotFoundError) async def item_not_found_handler(request: Request, exc: ItemNotFoundError): return JSONResponse( status_code=404, content={"message": f"Item with id {exc.item_id} not found."} ) items = {1: "apple", 2: "banana"} @app.get("/items/{item_id}") async def read_item(item_id: int): if item_id not in items: raise ItemNotFoundError(item_id) return {"item": items[item_id]}
OutputSuccess
Important Notes
Always return a proper HTTP status code with your error response.
Use JSONResponse to send JSON error messages that clients can understand.
Custom handlers help keep your API user-friendly and easier to debug.
Summary
Custom exception handlers catch errors and send friendly messages.
They improve user experience by explaining what went wrong.
FastAPI makes it easy to add these handlers for any error type.