FastAPI interview question · Most asked

How do you handle errors and customize error responses in FastAPI?

Summary

Raise HTTPException(status_code, detail) for expected errors, define domain exceptions with @app.exception_handler(MyError) to map them to responses, and override RequestValidationError handling to customize 422 payloads.

Longer Answer

Keep domain code framework-agnostic by raising your own exceptions (OrderNotFound) and translating them at the API boundary. A catch-all handler for Exception should log with a request ID and return a generic 500 without internals. Consider RFC 9457 Problem Details as a consistent error format.

Code Example

class OrderNotFound(Exception):
    def __init__(self, order_id: int):
        self.order_id = order_id

@app.exception_handler(OrderNotFound)
async def order_not_found(request, exc: OrderNotFound):
    return JSONResponse(status_code=404, content={"title": "Order not found", "order_id": exc.order_id})

Key Points

  • HTTPException for HTTP-level errors
  • Exception handlers map domain errors
  • Custom RequestValidationError handler
  • Never leak stack traces

More most-asked FastAPI questions

← All FastAPI questions