Custom exception handlers let you control how your app responds when errors happen. This helps you give clear, friendly messages instead of confusing errors.
Custom exception handlers in FastAPI
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
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
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}"} )
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."} )
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]}
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.
Practice
1. What is the main purpose of a custom exception handler in FastAPI?
easy
Solution
Step 1: Understand what exception handlers do
They catch errors that happen during request processing.Step 2: Identify the benefit of custom handlers
They allow sending clear, friendly messages instead of default error pages.Final Answer:
To catch specific errors and return user-friendly responses -> Option AQuick Check:
Custom handlers improve user experience = B [OK]
Hint: Custom handlers catch errors and explain them clearly [OK]
Common Mistakes:
- Thinking they fix bugs automatically
- Confusing with logging or performance tools
- Assuming they speed up requests
2. Which of the following is the correct way to register a custom exception handler in FastAPI?
easy
Solution
Step 1: Recall FastAPI method for adding handlers
FastAPI usesadd_exception_handlerto register handlers.Step 2: Check method names in options
Only app.add_exception_handler(MyException, handler_function) uses the correct method name and parameters.Final Answer:
app.add_exception_handler(MyException, handler_function) -> Option AQuick Check:
Correct method is add_exception_handler = D [OK]
Hint: Use add_exception_handler to register custom handlers [OK]
Common Mistakes:
- Using wrong method names like register_handler
- Confusing decorator syntax with registration
- Passing wrong parameters order
3. Given this code snippet, what will be the HTTP status code returned when
MyException is raised?
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
app = FastAPI()
class MyException(Exception):
pass
@app.exception_handler(MyException)
async def my_exception_handler(request: Request, exc: MyException):
return JSONResponse(status_code=418, content={"message": "Custom error occurred"})
@app.get("/test")
async def test():
raise MyException()medium
Solution
Step 1: Identify the status code in the handler
The handler returns a JSONResponse withstatus_code=418.Step 2: Understand what happens when exception is raised
RaisingMyExceptiontriggers the handler, which sends the 418 status.Final Answer:
418 -> Option BQuick Check:
Handler sets status 418 = A [OK]
Hint: Check the status_code in JSONResponse inside handler [OK]
Common Mistakes:
- Assuming default 500 error code
- Confusing 404 with missing route
- Ignoring custom status_code in handler
4. What is wrong with this FastAPI custom exception handler code?
from fastapi import FastAPI
app = FastAPI()
class CustomError(Exception):
pass
@app.exception_handler(CustomError)
def handler(exc: CustomError):
return {"error": "Something went wrong"}medium
Solution
Step 1: Check handler function signature
FastAPI expects async handler with parameters (Request, Exception).Step 2: Identify missing Request and async
The handler lacks the Request parameter and is not async.Final Answer:
Handler function must be async and accept Request parameter -> Option CQuick Check:
Handler signature requires async and Request = C [OK]
Hint: Handler must be async and take Request as first argument [OK]
Common Mistakes:
- Making handler synchronous
- Omitting Request parameter
- Thinking exception must inherit HTTPException
5. You want to create a custom exception handler in FastAPI that returns a JSON response with a dynamic message and a 400 status code whenever
ValueError is raised. Which code snippet correctly implements this?hard
Solution
Step 1: Check correct decorator and function signature
Use @app.exception_handler with async function taking (Request, Exception).Step 2: Verify JSONResponse usage and status code
Return JSONResponse with status_code=400 and content with error message.Step 3: Identify correct option
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": str(exc)}) matches all requirements exactly.Final Answer:
A -> Option DQuick Check:
Correct async handler with JSONResponse and status_code=400 = A [OK]
Hint: Use async handler with JSONResponse and status_code param [OK]
Common Mistakes:
- Using synchronous handler
- Missing Request parameter
- Wrong decorator or status code parameter name
- Returning dict instead of JSONResponse
