One Place to Turn Exceptions into Responses
Design a clean domain exception hierarchy, decouple business logic from HTTP status codes, and translate exceptions into RFC 9457 responses using centralised FastAPI exception handlers.
Contentsand lesson path
On this page
- Why it matters
- Keeping business code free of HTTP
- Designing a domain exception hierarchy
- Centralised exception handlers in FastAPI
- Check your understanding
- Apply it
- Review prompt
Lessons of Error Handling & Structured Logging
- Expected Errors, Bugs and Outages Concept · 15 min
- One Place to Turn Exceptions into Responses Worked example · 25 min
- When the Database or an Upstream API Fails Concept · 20 min
- Lab: Structured Logs with Request IDs Lab · 25 min
- Check: Triage an Incident from the Logs Knowledge check · 6 questions
What you will learn
- Map domain and infrastructure exceptions to HTTP responses in one place, returning Problem Details bodies without leaking stack traces or internal data.
Prerequisites: FastAPI Fundamentals
01. Why it matters
When building production web applications, backend teams often meet the same anti-pattern: error handling logic scattered across dozens of individual route handlers. In one endpoint, a software engineer wraps a database query inside an ad-hoc try/except block and returns a raw dictionary with an arbitrary error string. In another endpoint, an engineer raises fastapi.HTTPException(status_code=404). In a third endpoint, an unexpected exception escapes entirely, and the framework answers with a plain-text Internal Server Error.
Scattered error handling leads to three problems:
- Inconsistent client contracts: Mobile and web front-end developers must write custom parsing logic for every single endpoint because payload keys vary from
{"error": "..."}to{"message": "..."}or{"detail": "..."}. - Coupling to the web framework: When domain services or repository classes raise
HTTPException, business logic depends on one web framework. Core business functions cannot be safely reused inside asynchronous message consumers (like Celery or RabbitMQ workers), database migration scripts, or command-line administration tools. - Accidental security leaks: Without one central boundary, an unhandled database exception or connection timeout can leak internal SQL statements, schema table names, file system paths, or credential fragments directly to untrusted external clients.
02. Keeping business code free of HTTP
Business code should not know about HTTP. The rules of your domain, such as "a balance cannot go below zero", are the same whether the call comes from a web request, a background job or a test, so the code that enforces them should not mention status codes, request headers, cookies or JSON formats. Architecture styles such as Clean Architecture and ports and adapters (also called hexagonal architecture) make this a rule, but the idea is useful without adopting either.
In practice, error handling splits across three layers:
- Domain and service layer: checks the business rules. When an operation cannot proceed (for instance, a customer tries to withdraw more than their balance), it raises a Python exception that names the problem, such as
InsufficientFundsError. The exception carries domain data (the account ID, the balance, the amount asked for) but nothing about HTTP. - Exception handlers at the edge of the app: translate. They catch domain exceptions and turn them into HTTP responses in the RFC 9457 Problem Details format.
- Routes (the HTTP layer): stay short. A route reads its inputs, calls the service and returns the success result, without a
try/exceptaround every call.
03. Designing a domain exception hierarchy
The foundation of clean error handling is a structured exception hierarchy. Rather than raising generic RuntimeError or ValueError instances, we define a common base exception class for our application along with specialised subclasses representing distinct failure categories.
Here is a small domain exception hierarchy defined in app/exceptions.py:
class AppError(Exception):
"""Base class for all business domain errors in the application."""
def __init__(self, message: str, code: str = "app_error") -> None:
super().__init__(message)
self.message = message
self.code = code
class NotFoundError(AppError):
"""Raised when a requested domain entity does not exist."""
def __init__(self, entity: str, identifier: str | int) -> None:
super().__init__(
f"{entity} with identifier {identifier} was not found",
code="not_found",
)
self.entity = entity
self.identifier = identifier
class ConflictError(AppError):
"""Raised when an operation conflicts with existing system state."""
def __init__(self, message: str, field: str | None = None) -> None:
super().__init__(message, code="conflict")
self.field = field
class InsufficientFundsError(AppError):
"""Raised when an account does not have sufficient balance."""
def __init__(self, account_id: str, balance: int, requested: int) -> None:
super().__init__(
f"Account {account_id} requires {requested} but has {balance}",
code="insufficient_funds",
)
self.account_id = account_id
self.balance = balance
self.requested = requestedNotice that AppError and all its descendants inherit directly from Python's standard Exception. A service function such as order_service.cancel_order(order_id) can freely raise NotFoundError("Order", order_id).
Because this exception contains only business data, unit tests can assert on exc.entity and exc.identifier without spinning up an HTTP server or mocking request objects. Furthermore, if a background cron job invokes order_service.cancel_order(), it can catch NotFoundError and handle it according to batch processing requirements without encountering HTTP status codes.
04. Centralised exception handlers in FastAPI
In FastAPI, the mapping from domain exceptions to HTTP responses takes place in exactly one place: the application boundary via app.exception_handler(). When a route or a dependency raises an exception, FastAPI looks up a handler by the exception's class and dispatches it there.
FastAPI traverses the exception class hierarchy to find the closest matching handler. If a handler is registered for NotFoundError, it will catch instances of NotFoundError. If an unhandled exception occurs, it falls back to the top-level Exception handler.
Where the handlers run matters. Handlers for specific classes run in Starlette's ExceptionMiddleware, which sits inside your own middleware, so an exception raised in your middleware never reaches the NotFoundError or ConflictError handler; only the Exception handler applies. That one is special: Starlette runs it in the outermost ServerErrorMiddleware, sends its response, then re-raises the exception so the server still logs a traceback. Two consequences follow. The 500 response is built outside CORSMiddleware and your request-ID middleware, so it gets no CORS headers and must set X-Request-ID itself. And in tests the default TestClient re-raises the exception; create TestClient(app, raise_server_exceptions=False) to see the 500 body.
Here is the complete implementation of centralised exception handlers in app/handlers.py:
import logging
import uuid
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from app.exceptions import (
AppError,
ConflictError,
InsufficientFundsError,
NotFoundError,
)
logger = logging.getLogger("app.errors")
def register_exception_handlers(app: FastAPI) -> None:
@app.exception_handler(NotFoundError)
async def not_found_handler(request: Request, exc: NotFoundError):
return JSONResponse(
status_code=404,
media_type="application/problem+json",
content={
"type": "https://api.example.com/errors/not-found",
"title": "Resource Not Found",
"status": 404,
"detail": exc.message,
"instance": str(request.url.path),
"code": exc.code,
},
)
@app.exception_handler(ConflictError)
async def conflict_handler(request: Request, exc: ConflictError):
return JSONResponse(
status_code=409,
media_type="application/problem+json",
content={
"type": "https://api.example.com/errors/conflict",
"title": "State Conflict",
"status": 409,
"detail": exc.message,
"instance": str(request.url.path),
"code": exc.code,
},
)
@app.exception_handler(InsufficientFundsError)
async def funds_handler(request: Request, exc: InsufficientFundsError):
return JSONResponse(
status_code=422,
media_type="application/problem+json",
content={
"type": "https://api.example.com/errors/insufficient-funds",
"title": "Insufficient Account Balance",
"status": 422,
"detail": exc.message,
"instance": str(request.url.path),
"balance": exc.balance,
"requested": exc.requested,
},
)
@app.exception_handler(RequestValidationError)
async def validation_handler(request: Request, exc: RequestValidationError):
errors = [
{
"field": ".".join(str(loc) for loc in err["loc"]),
"issue": err["msg"],
}
for err in exc.errors()
]
return JSONResponse(
status_code=422,
media_type="application/problem+json",
content={
"type": "https://api.example.com/errors/validation-failed",
"title": "Invalid Request Parameters",
"status": 422,
"detail": "One or more input fields failed validation rules",
"instance": str(request.url.path),
"invalid_params": errors,
},
)
@app.exception_handler(Exception)
async def unhandled_exception_handler(request: Request, exc: Exception):
# Set by the request-ID middleware; never trust the raw header here
req_id = getattr(request.state, "request_id", None) or uuid.uuid4().hex
logger.exception(
"Unhandled server exception during request",
extra={"request_id": req_id, "path": str(request.url.path)},
)
return JSONResponse(
status_code=500,
media_type="application/problem+json",
headers={"X-Request-ID": req_id},
content={
"type": "https://api.example.com/errors/internal-server-error",
"title": "Internal Server Error",
"status": 500,
"detail": "An unexpected error occurred. Please contact support.",
"request_id": req_id,
},
)Look closely at the design of unhandled_exception_handler and validation_handler:
- Information containment on 500 errors: When an unforeseen system crash occurs (such as a database connection drop or unexpected
TypeError), the server logs the full traceback withlogger.exception()under the request ID. That ID comes fromrequest.state.request_id, which the request-ID middleware from the structured logging lab sets for every request: it reuses an incomingX-Request-IDonly if it is a short ID of letters, digits and hyphens, and otherwise generates one. Most clients send no header, and an unchecked header would put attacker-chosen text into your logs. Store the ID onrequest.stateas well as in the ContextVar, because this handler runs after the middleware has returned and reset the ContextVar. However, the client receives only an opaque message: "An unexpected error occurred." The response carries no SQL, table names or stack frames. - Standardised validation errors: FastAPI's default Pydantic validation response formats errors into a non-standard list of dictionaries. By intercepting
RequestValidationError, we normalise validation errors into an RFC 9457 envelope containing aninvalid_paramsarray. Client applications can immediately map these field issues to user interface form inputs. - Correlation tracing: Both client and server share the identical
request_id. When a user contacts support with an error report, support staff can find the exact log line and full stack trace in a central log store such as Elasticsearch or Grafana Loki.
05. Check your understanding
06. Apply it
Create an app/exceptions.py module with AppError, NotFoundError, and ConflictError classes. In your FastAPI setup, implement register_exception_handlers to convert these domain errors into application/problem+json responses. Write a pytest test using TestClient verifying that raising NotFoundError from a route returns HTTP 404 with standard RFC 9457 fields.
With this boundary between domain rules and transport protocols in place, the same service code runs unchanged from background message consumers, CLI commands and database maintenance jobs. In the next lesson, you will learn how to handle failing dependencies with timeouts, retries, and fallbacks.
07. Review prompt
Explain why raising HTTPException inside service layer functions is considered an architectural anti-pattern. Describe the responsibilities of app.exception_handler(), and detail what information an unhandled 500 handler should log internally versus what it should send to the client.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.