How to Create Custom Exception Handler in FastAPI
In FastAPI, create a custom exception handler by defining a function with the
@app.exception_handler(ExceptionType) decorator. This function receives the request and exception, then returns a custom JSONResponse or other response type to control error output.Syntax
To create a custom exception handler in FastAPI, use the @app.exception_handler() decorator with the exception class you want to handle. Define a function that takes request and exc (the exception instance) as parameters. Return a response like JSONResponse with your custom message and status code.
@app.exception_handler(ExceptionType): Registers the handler for the specified exception.async def handler(request, exc):: The handler function signature.return JSONResponse(status_code=..., content=...): Sends the custom error response.
python
from fastapi import FastAPI, Request from fastapi.responses import JSONResponse app = FastAPI() @app.exception_handler(ValueError) async def value_error_handler(request: Request, exc: ValueError): return JSONResponse( status_code=400, content={"detail": str(exc)} )
Example
This example shows how to catch a ValueError raised in a route and return a custom JSON error message with status code 400.
python
from fastapi import FastAPI, Request from fastapi.responses import JSONResponse app = FastAPI() @app.exception_handler(ValueError) async def value_error_handler(request: Request, exc: ValueError): return JSONResponse( status_code=400, content={"error": "A value error occurred", "message": str(exc)} ) @app.get("/items/{item_id}") async def read_item(item_id: int): if item_id < 0: raise ValueError("Item ID must be positive") return {"item_id": item_id}
Output
GET /items/-1
Response status: 400
{
"error": "A value error occurred",
"message": "Item ID must be positive"
}
Common Pitfalls
- Not using
async deffor the handler function can cause issues since FastAPI expects async handlers. - Forgetting to return a proper response like
JSONResponseleads to default error pages. - Registering the handler for the wrong exception type means your handler won't be called.
- Raising exceptions without catching them or without a handler results in generic 500 errors.
python
from fastapi import FastAPI, Request from fastapi.responses import JSONResponse app = FastAPI() # Wrong: missing async @app.exception_handler(ValueError) def wrong_handler(request: Request, exc: ValueError): return JSONResponse(status_code=400, content={"detail": str(exc)}) # Correct: @app.exception_handler(ValueError) async def correct_handler(request: Request, exc: ValueError): return JSONResponse(status_code=400, content={"detail": str(exc)})
Quick Reference
Use this quick guide to create custom exception handlers in FastAPI:
- Decorator:
@app.exception_handler(ExceptionType) - Handler function: async function with
requestandexcparameters - Return:
JSONResponseor other response with custom status and content - Common exceptions:
HTTPException,ValueError, custom exceptions
Key Takeaways
Use @app.exception_handler(ExceptionType) to register a custom handler for that exception.
Define the handler as an async function accepting request and exception parameters.
Return a JSONResponse with your custom error message and HTTP status code.
Ensure the exception type matches what you want to catch to trigger your handler.
Avoid missing async or returning wrong response types to prevent fallback errors.