
FastAPI
Learn the fundamentals of custom exceptions in FastAPI.
Custom exceptions allow you to define domain-specific errors for your API. They enable you to handle application-specific error scenarios and provide meaningful error responses to clients.
In this section, you'll understand:
class ItemNotFoundError(Exception):
def __init__(self, item_id: int):
self.item_id = item_id
self.message = f"Item with ID {item_id} not found"
class InsufficientInventoryError(Exception):
def __init__(self, requested: int, available: int):
self.requested = requested
self.available = available
self.message = f"Need {requested} items but only {available} available"from fastapi import FastAPI
from fastapi.responses import JSONResponse
app = FastAPI()
@app.exception_handler(ItemNotFoundError)
async def item_not_found_handler(request, exc):
return JSONResponse(
status_code=404,
content={
"error": "ItemNotFound",
"detail": exc.message,
"item_id": exc.item_id
}
)
@app.exception_handler(InsufficientInventoryError)
async def insufficient_inventory_handler(request, exc):
return JSONResponse(
status_code=400,
content={
"error": "InsufficientInventory",
"detail": exc.message,
"requested": exc.requested,
"available": exc.available
}
)class UserAlreadyExistsError(Exception):
def __init__(self, email: str):
self.email = email
self.message = f"User with email {email} already exists"
@app.exception_handler(UserAlreadyExistsError)
async def user_exists_handler(request, exc):
return JSONResponse(
status_code=409,
content={"error": "UserAlreadyExists", "detail": exc.message}
)
@app.post("/users/")
async def create_user(user: UserCreate):
if db.user_exists(user.email):
raise UserAlreadyExistsError(user.email)
return db.create_user(user)Custom exceptions are essential for:
Example - Payment processing:
class PaymentFailedError(Exception):
def __init__(self, reason: str):
self.reason = reason
@app.exception_handler(PaymentFailedError)
async def payment_failed_handler(request, exc):
logger.error(f"Payment failed: {exc.reason}")
return JSONResponse(status_code=402, content={"error": exc.reason})
@app.post("/checkout")
async def checkout(order: Order):
if not validate_card(order.card):
raise PaymentFailedError("Invalid card number")
process_payment(order)
return {"status": "success"}Ready to explore more? Check out the advanced section for production patterns and edge cases.
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward