Recipe 5.4 · Python
Global Exception Handling with ProblemDetails
The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.
- Problem
- The way it's often written
- The improved recipe
- How it works
- Variations and pitfalls
- On .NET Framework
Problem
Every controller action has its own try/catch that logs and returns a hand-built error
object. The shapes differ between endpoints, some return HTML error pages to API clients, and a
few return the full exception text, connection string fragment included.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
Requirements: Python 3.12+. Install: pip install fastapi
"""The same try/except pasted into every controller action
Source: ImproveCode, Chapter 5, Recipe 5.4 "Global Exception Handling with ProblemDetails"
Section: The way it's often written
Book page: 108 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
A FastAPI route replaces the MVC action; traceback.format_exc() reproduces ex.ToString()
leaking to the client.
"""
from __future__ import annotations
import traceback
from typing import Any
from fastapi import APIRouter
router = APIRouter()
_service: Any = None
LogHelper: Any = None
# Not this: the same try/except pasted into every action.
@router.get("/customers/{id}")
def get_customer(id: int) -> Any:
try:
return _service.get(id)
except Exception as ex:
LogHelper.error("GetCustomer", ex)
return {"success": False, "error": traceback.format_exc()}
The improved recipe
Handle exceptions in one place with IExceptionHandler (ASP.NET Core 8 and later) and return RFC
9457 ProblemDetails JSON. Map the exceptions from Recipe 5.3 to status codes there.
In Program.cs, as a usage snippet:
A request for a missing customer now returns:
{
"type": "https://tools.ietf.org/html/rfc9110#section-15.5.5",
"title": "Not found",
"status": 404,
"detail": "Customer '42' was not found.",
"instance": "/customers/42",
"traceId": "4bf92f3577b34da6a3ce929d0e0e4736",
"errorCode": "not_found"
}
Requirements: Python 3.12+. Install: pip install fastapi starlette
"""Global exception handler that returns RFC 7807 problem details
Source: ImproveCode, Chapter 5, Recipe 5.4 "Global Exception Handling with ProblemDetails"
Section: The improved recipe
Book page: 109-110 -- original C# listing
Converted from C# to Python.
FastAPI exception handlers replace IExceptionHandler/UseExceptionHandler; a JSONResponse
with media type application/problem+json replaces IProblemDetailsService; an
APP_ENVIRONMENT variable stands in for IHostEnvironment.IsDevelopment(); a handler for
StarletteHTTPException plays the role of UseStatusCodePages.
"""
from __future__ import annotations
import logging
import os
import traceback
import uuid
from typing import Any
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
logger = logging.getLogger(__name__ + ".AppExceptionHandler")
class AppException(Exception):
"""See p106_r5_3_app_exception_hierarchy.py (Recipe 5.3)."""
def __init__(self, error_code: str, message: str) -> None:
super().__init__(message)
self.error_code = error_code
class NotFoundException(AppException): ...
class ConflictException(AppException): ...
class BusinessRuleException(AppException): ...
def _is_development() -> bool:
return os.environ.get("APP_ENVIRONMENT", "Production") == "Development"
def _trace_id(request: Request) -> str:
# Set by the correlation middleware (Recipe 4.3) if present.
return getattr(request.state, "correlation_id", None) or uuid.uuid4().hex
def _problem(request: Request, status: int, title: str,
detail: str | None, **extensions: Any) -> JSONResponse:
body: dict[str, Any] = {
"type": f"https://tools.ietf.org/html/rfc9110#status-{status}",
"title": title,
"status": status,
"instance": request.url.path,
}
if detail is not None:
body["detail"] = detail
body["traceId"] = _trace_id(request)
body.update(extensions)
return JSONResponse(body, status_code=status,
media_type="application/problem+json")
async def app_exception_handler(request: Request, exception: Exception) -> JSONResponse:
match exception:
case NotFoundException():
status, title = 404, "Not found"
case ConflictException():
status, title = 409, "Conflict"
case BusinessRuleException():
status, title = 422, "Business rule violated"
case _:
status, title = 500, "An unexpected error occurred"
if status >= 500:
logger.error("Unhandled exception on %s %s",
request.method, request.url.path, exc_info=exception)
else:
logger.info("Request failed with %s: %s", status, exception)
# Only messages written for users are shown.
detail = str(exception) if isinstance(exception, AppException) else None
extensions: dict[str, Any] = {}
if isinstance(exception, AppException):
extensions["errorCode"] = exception.error_code
if status >= 500 and _is_development():
detail = "".join(traceback.format_exception(exception))
return _problem(request, status, title, detail, **extensions)
async def status_code_handler(request: Request, exc: StarletteHTTPException) -> JSONResponse:
"""ProblemDetails for bare 404s etc. (UseStatusCodePages)."""
return _problem(request, exc.status_code, str(exc.detail), None)
def add_app_error_handling(app: FastAPI) -> FastAPI:
app.add_exception_handler(Exception, app_exception_handler)
app.add_exception_handler(StarletteHTTPException, status_code_handler) # type: ignore[arg-type]
return app
Requirements: Python 3.12+. Install: pip install fastapi
"""Registering global error handling and correlation IDs at startup
Source: ImproveCode, Chapter 5, Recipe 5.4 "Global Exception Handling with ProblemDetails"
Section: The improved recipe
Book page: 110 -- original C# listing
Converted from C# to Python.
FastAPI exception handlers wrap the whole app, so "first in the pipeline" is automatic;
add_app_error_handling and use_correlation_id come from
p109_r5_4_global_problem_details_handler.py and p086_r4_3_correlation_id_middleware_propagation.py.
"""
from __future__ import annotations
from typing import Callable
from fastapi import FastAPI
def build_app(
add_app_error_handling: Callable[[FastAPI], FastAPI],
use_correlation_id: Callable[[FastAPI], FastAPI],
) -> FastAPI:
app = FastAPI()
add_app_error_handling(app) # first in the pipeline
use_correlation_id(app) # Chapter 4, Recipe 4.3
return app
How it works
UseExceptionHandler() with no arguments catches any exception that escapes the rest of the
pipeline and passes it to each registered IExceptionHandler in order until one returns true.
Actions and services can now just throw. The per-action try/catch blocks go away, and so do
the inconsistent error shapes.
The switch expression is the whole policy in a few lines. Expected failures get a 4xx status and their message. Everything else gets a 500 with a generic title and no detail, because an unknown exception's message may contain anything. In Development the full exception text is included so you don't have to dig through logs on your own machine.
Only 500s are logged as errors. A 404 for a missing record is a normal outcome, and logging it at
Error floods dashboards and trains people to ignore red. The traceId is the correlation ID
from Chapter 4, so a support call that starts with "my reference is 4bf92f..." leads straight to
the request's log lines.
IProblemDetailsService.TryWriteAsync writes application/problem+json, fills in the standard
type link for the status code, and respects any customization registered with
AddProblemDetails. UseStatusCodePages gives bare status results (a 404 from routing, a 405)
the same JSON shape.
Variations and pitfalls
- Register it first in the pipeline so it also catches failures in other middleware.
- For MVC or Razor Pages apps that serve HTML, the same handler works. Check the
Acceptheader and redirect to an error page that displays thetraceId, or useUseExceptionHandler("/Error")for browser routes. - If the response has already started (a streaming download failed halfway), nothing can change the status code. The handler still logs; the client sees a truncated response.
- You can register several handlers, for example one for
DbUpdateConcurrencyExceptionthat returns 409, before the general one. They run in registration order. - Don't map
ArgumentExceptionto 400 globally. AnArgumentExceptiondeep in your code is usually a bug, not bad client input. Validate input at the boundary (Chapter 8) instead.
On .NET Framework
ASP.NET MVC 5 and Web API 2 offer HandleErrorAttribute, ExceptionFilterAttribute and
IExceptionHandler (in System.Web.Http.ExceptionHandling). The same mapping logic fits in a Web
API ExceptionHandler subclass registered with
config.Services.Replace(typeof(IExceptionHandler), ...). For Web Forms, Application_Error in
Global.asax is the single place to log and redirect.