Skip to content

Unified error format and exception handling

Introduction

Return errors in a consistent structure no matter where they occur (RFC 9457 Problem Details recommended), and catch exceptions globally instead of writing ad hoc handling everywhere.

Why use it

  • Easier for callers: the frontend only needs one error-parsing path.
  • Safer: show users only what they should see; keep stacks, SQL, and server paths in logs (see Logging).
  • Easier to trace: include a trace id in the error so when a user reports it, you can find it in the logs immediately.

Standard format: Problem Details

RFC 9457 (which replaces RFC 7807) is an industry standard for error response bodies. Use Content-Type: application/problem+json:

{
"type": "https://example.com/errors/out-of-stock",
"title": "Out of stock",
"status": 409,
"detail": "Product A has only 2 left; you asked for 5.",
"instance": "/orders/123",
"traceId": "00-abc123..."
}

type identifies the error kind, title is a short summary, detail is the concrete case, and status is the HTTP status code. You can add custom fields such as traceId.

How to do it

  1. Global catch-all: catch every unhandled exception in one place and turn it into 500 + Problem Details.
  2. Separate expected from unexpected: bad parameters and missing resources are expected → 4xx; code bugs are unexpected → 500.
  3. Vague outside, detailed inside: a 500 tells the user only “server error, id xxx”; the full stack goes to the logs.
  4. Keep status code and body aligned; see REST API design for how to choose them.

Component comparison

ProblemDetails + IExceptionHandler

Built into the frameworkOpsLow

ASP.NET Core's built-in standard error format (Problem Details, an industry-standard error JSON structure), combined with a global exception handler that catches every unhandled error.

Best forNew ASP.NET Core API projects.

Avoid whenThe project is stuck on a version older than .NET 8 and will not upgrade soon.

Pros

The format is an industry standard, easy for frontends and third parties to understand

One global handler is the safety net, so business code needs no scattered try/catch

Built-in AddProblemDetails can attach trace information to errors automatically

Cons

IExceptionHandler requires .NET 8 or later; older versions need custom middleware

You write the mapping of which exception maps to which status code; the framework will not decide for you

Custom fields and unified error codes still need to be agreed on yourself

FastAPI exception handlers

Built into the frameworkOpsLow

Register with @app.exception_handler what to return when a certain kind of exception occurs in FastAPI, and decide the unified format yourself.

Best forPython API projects that use FastAPI.

Avoid whenThe project uses Django REST Framework; use its own exception handler mechanism instead.

Pros

Once a handler is registered, uncaught exceptions are still caught globally

Validation errors and business exceptions can be handled separately

You decide the response body, which makes one error format easy

Cons

The default 422 format and HTTP exception format do not match

There is no ready-made standard error type, so you assemble the shape

Forgetting to register one exception type lets the default format leak out

Hand-written unified envelope ({ code, message, data })

Hand-rolledOpen sourceOpsLow

The team defines a fixed wrapper that holds both successes and failures, using business error codes to represent specific errors.

Best forInternal projects that only serve their own frontend and where the team already has conventions.

Avoid whenYou need to expose a public API, or want generic tools (gateways, monitoring) to detect failures by status code.

Pros

The frontend parses one envelope, so the team can line up easily

Business error codes can split errors more finely

It is not tied to a language or a framework, so internal projects can adopt it

Cons

It is not an industry standard, so outside callers have to read your docs

It easily becomes always returning 200, and monitoring cannot see the failure

The error-code table needs long-term care and gets messy over time

thiserror + IntoResponse

Open-source libraryOpen sourceOpsLow

Define errors with thiserror and implement IntoResponse so every route returns one error shape.

Best forUniform error responses for any Axum API.

Avoid whenClients already depend heavily on a different error structure.

Pros

Error types are centralized and routes return Result

Map them to one JSON structure

The source error is kept for logs

Cons

Business error codes need extra fields you define

You must decide which details may leave the server

A missing IntoResponse becomes a plain-text 500

Official docs ↗

Unified error-handling hook

Open-source libraryOpen sourceOpsLow

Use the framework's global hook (Fastify setErrorHandler, NestJS ExceptionFilter, Hono onError) to centrally turn exceptions into a uniform error response.

Best forUniform error responses for any TypeScript backend.

Avoid whenA specific error specification is already mandated and a gateway converts errors uniformly.

Pros

All error exits are centralized in one place with a consistent format

Business code just throws a custom error carrying an error code

Logging with the request ID can be handled here uniformly

Cons

You must define the error code system and response structure yourself

You must distinguish error messages that may be exposed externally from those that may not

A missing await in async code bypasses the handler

Error middleware + errors.Is / As

Open-source libraryOpen sourceOpsLow

Handlers return an error, and a unified middleware maps it to a uniform response structure using errors.Is / errors.As.

Best forUniform error responses for any Go backend.

Avoid whenA unified RPC / gateway layer already converts errors.

Pros

Error handling logic is centralized, keeping handlers concise

Uses standard library error wrapping to preserve call context

Easy to log with the request ID

Cons

You must define the handler signature and error types yourself

The standard library provides no uniform error response specification

Needs discipline to ensure every error is mapped

Checklist

  • All error responses share one structure (Problem Details recommended)
  • A global exception handler is in place as a catch-all
  • 500 responses never leak stacks, SQL, or paths
  • Error responses carry a trace id that matches the logs
  • Status codes match the error type; never wrap errors in 200