Search Topics

Search across all FastAPI topics

GitHub

Error Handling

2 topics

Graceful error handling is essential for production APIs. Learn how to raise HTTP exceptions and create custom handlers for consistent error responses.

Tip

Always use HTTPException for expected errors (not found, unauthorized). Reserve custom exception handlers for unexpected errors and consistent error formatting across your entire API.

How Errors Flow

Step 1: Request

A client request arrives at your endpoint.

Explore: HTTP Status Codes

These are the patterns that trip up developers most often. Switch between Wrong and Fixed to compare the code side by side.

1
Returning errors instead of raising
Using return for error responses instead of HTTPException
Don't do this
main.py
@app.get("/items/{id}")
async def get_item(id: int):
    item = db.get(id)
    if not item:
        return {"error": "Not found"}  # Wrong!
    return item
Returning an error dict gives a 200 status code, confusing clients. Always raise HTTPException to set the correct status code and let FastAPI format the error response properly.