Skip to content

10.8 — ProblemDetails and Consistent Error Contracts

← Roadmap · Section: 10. Web API Design and REST Prev: 10.7 Pagination and filtering · Next: 10.9 OpenAPI and Swagger

Markers: ⭐ 💻 · Confidence: 🔴 · Last reviewed: —


TL;DR

ProblemDetails is a standard JSON shape for API errors, defined by RFC 7807/9457 and built into ASP.NET Core.

  • Five standard fields: type, title, status, detail, instance — plus any extensions you add.
  • The point is one error shape across the whole API, so clients write one error handler instead of one per endpoint.
  • Never put an exception message in detail on a 500. Return a traceId and put the real detail in the logs.

Definitions

Term What it is What it means
ProblemDetails a C# class (RFC 7807/9457) The standard error body shape.
ValidationProblemDetails a C# class ProblemDetails plus a per-field errors dictionary.
type a field A URI identifying the kind of error. The machine-readable key.
title a field Short human summary. Should not change per occurrence.
status a field The HTTP status code, duplicated in the body.
detail a field What went wrong this time.
instance a field A URI for this specific occurrence — usually the request path.
Extensions a dictionary Extra fields you add — traceId, errors, error codes.
application/problem+json a media type The content type for a problem response.
AddProblemDetails() a DI extension (.NET 7+) Registers the default problem details service.
IProblemDetailsService an interface (.NET 7+) The hook for writing problem responses.
IExceptionHandler an interface (.NET 8+) A typed, chained exception handler.
UseExceptionHandler() a middleware registration Catches unhandled exceptions.

The concept

Without a convention, an API's errors drift into three or four shapes:

{ "error": "Not found" }
{ "message": "Validation failed", "fields": ["email"] }
{ "Errors": { "Email": ["Invalid"] } }
"Something went wrong"

Every client then writes a parser per endpoint, and gets it wrong for the endpoint added last week.

ProblemDetails is the agreed shape:

{
  "type": "https://api.example.com/errors/insufficient-funds",
  "title": "Insufficient funds",
  "status": 409,
  "detail": "Account 4711 has a balance of £30.00; the transfer requires £50.00.",
  "instance": "/api/accounts/4711/transfers",
  "traceId": "00-8fa1c2d3e4f5-9a8b7c6d5e4f-01",
  "balance": 30.00,
  "required": 50.00
}

The division of labour is what makes it useful:

  • type is what code branches on. It is stable, so a client can match it.
  • title is stable text for the same type. Safe to show, safe to log-group.
  • detail is about this occurrence, with the specifics filled in.
  • Extensions carry machine-readable specifics — balance and required here — so the client does not parse them out of the prose.

⚠️ type is a URI, not necessarily a URL that resolves. It is an identifier. Making it a real documentation page is nice; it is not required, and the default ASP.NET Core values point at the RFC section for the status code.

The analogy

A doctor's note. title is the diagnosis, detail is your specific case, type is the ICD code insurers actually process, and instance is the visit reference. The code is what systems act on; the prose is for humans.


How it works

It is already on by default (partly)

With [ApiController], error status codes already return ProblemDetails (10.4):

return NotFound();
{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.4",
  "title": "Not Found",
  "status": 404,
  "traceId": "00-8fa1c…-01"
}

And validation failures return ValidationProblemDetails, which adds errors:

{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "errors": {
    "Email":    [ "The Email field is not a valid e-mail address." ],
    "Quantity": [ "The field Quantity must be between 1 and 100." ]
  }
}

⚠️ What is not covered by default is the unhandled exception. That still produces a bare 500, with the developer exception page in development and an empty body in production. Wiring that up is the work.

.NET 7+ — AddProblemDetails

builder.Services.AddProblemDetails(options =>
{
    options.CustomizeProblemDetails = context =>
    {
        // Every problem response gets a correlation ID — this is the single most
        // useful field in the whole object for a support conversation
        context.ProblemDetails.Instance =
            $"{context.HttpContext.Request.Method} {context.HttpContext.Request.Path}";

        context.ProblemDetails.Extensions["traceId"] =
            Activity.Current?.Id ?? context.HttpContext.TraceIdentifier;

        context.ProblemDetails.Extensions["requestId"] = context.HttpContext.TraceIdentifier;
    };
});

var app = builder.Build();

app.UseExceptionHandler();     // now writes ProblemDetails for unhandled exceptions
app.UseStatusCodePages();      // and for bare status codes with no body (404 from routing)

⚠️ UseStatusCodePages() matters more than it looks. A 404 from routing — no endpoint matched at all — never reaches a controller, so [ApiController] cannot shape it. Without this, your API returns ProblemDetails for a controller's NotFound() and an empty body for a mistyped URL. Two shapes for the same status code.

.NET 8+ — IExceptionHandler

The modern way: typed handlers, tried in registration order.

public sealed class ValidationExceptionHandler : IExceptionHandler
{
    private readonly IProblemDetailsService _problemDetails;

    public ValidationExceptionHandler(IProblemDetailsService problemDetails)
        => _problemDetails = problemDetails;

    public async ValueTask<bool> TryHandleAsync(
        HttpContext context, Exception exception, CancellationToken ct)
    {
        // Return false → not ours, pass to the next handler in the chain
        if (exception is not DomainValidationException ve) return false;

        context.Response.StatusCode = StatusCodes.Status400BadRequest;

        return await _problemDetails.TryWriteAsync(new ProblemDetailsContext
        {
            HttpContext = context,
            ProblemDetails = new ProblemDetails
            {
                Type   = "https://api.example.com/errors/validation",
                Title  = "Validation failed",
                Status = StatusCodes.Status400BadRequest,
                Detail = ve.Message,
                Extensions = { ["errors"] = ve.Errors }
            }
        });
    }
}
// ⚠️ Order matters — first handler that returns true wins.
// Specific handlers first, the catch-all last.
builder.Services.AddExceptionHandler<ValidationExceptionHandler>();
builder.Services.AddExceptionHandler<NotFoundExceptionHandler>();
builder.Services.AddExceptionHandler<ConflictExceptionHandler>();
builder.Services.AddExceptionHandler<FallbackExceptionHandler>();

⚠️ If every handler returns false, the exception propagates and you get the default 500 with no body. The last handler in the chain must be an unconditional catch-all.

The deeper detail — what must never be in the body

⚠️ A 500's detail must not contain the exception message. Real examples of what leaks:

  • "Login failed for user 'sa'" — the database account name.
  • "Could not find file 'C:\inetpub\app\config\secrets.json'" — the deployment layout.
  • "A network-related error… server was not found" — internal hostnames.
  • Full stack traces — every framework and package version you run.

The correct shape:

{
  "type": "https://api.example.com/errors/internal",
  "title": "An unexpected error occurred",
  "status": 500,
  "detail": "The request could not be completed. Quote the traceId when contacting support.",
  "traceId": "00-8fa1c2d3-9a8b7c6d-01"
}

Generic to the caller, precise in the logs. The traceId links the two, which is exactly what distributed tracing gives you for free (18.7).

⚠️ 4xx detail is different — it should be specific, because the caller needs it to fix their request. "Quantity must be between 1 and 100" helps; "Bad request" does not. The rule is about our internals, not about being unhelpful.

⚠️ And error responses must not be cached. A cached 500 gets served to everyone. UseExceptionHandler sets no-cache headers; a hand-rolled handler must do it too (19.5).


Code

An end-to-end setup:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

builder.Services.AddProblemDetails(options =>
{
    options.CustomizeProblemDetails = ctx =>
    {
        ctx.ProblemDetails.Extensions["traceId"] =
            Activity.Current?.Id ?? ctx.HttpContext.TraceIdentifier;

        // Only in development — never expose the machine name in production
        if (ctx.HttpContext.RequestServices
               .GetRequiredService<IHostEnvironment>().IsDevelopment())
        {
            ctx.ProblemDetails.Extensions["machine"] = Environment.MachineName;
        }
    };
});

// Registration order = evaluation order
builder.Services.AddExceptionHandler<NotFoundExceptionHandler>();
builder.Services.AddExceptionHandler<ConflictExceptionHandler>();
builder.Services.AddExceptionHandler<FallbackExceptionHandler>();

var app = builder.Build();

app.UseExceptionHandler();
app.UseStatusCodePages();      // shapes routing 404s and other bodiless status codes

app.MapControllers();
app.Run();

The catch-all, which is where the security rule lives:

public sealed class FallbackExceptionHandler : IExceptionHandler
{
    private readonly IProblemDetailsService _problemDetails;
    private readonly ILogger<FallbackExceptionHandler> _log;
    private readonly IHostEnvironment _env;

    public FallbackExceptionHandler(
        IProblemDetailsService problemDetails,
        ILogger<FallbackExceptionHandler> log,
        IHostEnvironment env)
        => (_problemDetails, _log, _env) = (problemDetails, log, env);

    public async ValueTask<bool> TryHandleAsync(
        HttpContext context, Exception exception, CancellationToken ct)
    {
        var traceId = Activity.Current?.Id ?? context.TraceIdentifier;

        // The full exception goes to the LOGS, with the same traceId the caller receives
        _log.LogError(exception,
            "Unhandled exception {TraceId} for {Method} {Path}",
            traceId, context.Request.Method, context.Request.Path);

        context.Response.StatusCode = StatusCodes.Status500InternalServerError;

        return await _problemDetails.TryWriteAsync(new ProblemDetailsContext
        {
            HttpContext = context,
            ProblemDetails = new ProblemDetails
            {
                Type   = "https://api.example.com/errors/internal",
                Title  = "An unexpected error occurred",
                Status = StatusCodes.Status500InternalServerError,

                // ⚠️ The exception message ONLY outside production.
                // In production it leaks hostnames, paths and account names.
                Detail = _env.IsDevelopment()
                    ? exception.ToString()
                    : "The request could not be completed. Quote the traceId when contacting support.",

                Extensions = { ["traceId"] = traceId }
            }
        });
    }
}

Returning a domain error from an action, in the same shape:

[HttpPost("{id:int}/transfers")]
public async Task<IActionResult> Transfer(int id, TransferRequest req, CancellationToken ct)
{
    var result = await _accounts.TransferAsync(id, req, ct);
    if (result.Succeeded) return NoContent();

    return Problem(
        type:   "https://api.example.com/errors/insufficient-funds",
        title:  "Insufficient funds",
        detail: $"Account {id} has a balance of {result.Balance:C}; "
              + $"the transfer requires {req.Amount:C}.",
        statusCode: StatusCodes.Status409Conflict,
        extensions: new Dictionary<string, object?>
        {
            // Machine-readable — the client should not regex the detail string
            ["balance"]  = result.Balance,
            ["required"] = req.Amount,
            ["shortfall"] = req.Amount - result.Balance
        });
}

That extensions dictionary is the detail worth taking away. A client that needs the shortfall should read shortfall, not parse it out of an English sentence — which also means you can change the wording, or translate it, without breaking anyone.


Interview questions

Q: What is ProblemDetails?

A standard JSON error shape from RFC 7807, updated as 9457, and built into ASP.NET Core. It has five fields — type, title, status, detail, instance — plus arbitrary extensions. type is a URI identifying the kind of error and is what clients branch on; title is stable human text for that kind; detail describes this specific occurrence. The value is one error shape across the whole API, so a client writes one error handler rather than one per endpoint, and the extensions let you carry machine-readable specifics instead of making clients parse prose.

Q: Is it on by default?

Partly. With [ApiController], error status codes returned from actions already produce ProblemDetails, and validation failures produce ValidationProblemDetails with a per-field errors dictionary. What is not covered is unhandled exceptions, which give a bare 500, and 404s from routing, which never reach a controller at all. So you need UseExceptionHandler for the first and UseStatusCodePages for the second — otherwise the same API returns ProblemDetails for one 404 and an empty body for another.

Q: What should never go in the error body?

Anything internal, on a 5xx. Exception messages leak database account names, file paths and internal hostnames; stack traces leak your entire dependency list. The pattern is a generic detail plus a traceId extension, with the full exception logged against that same ID so support can find it. 4xx is the opposite — detail there should be as specific as possible, because the caller needs it to fix their request. The rule is about hiding our internals, not about being unhelpful.

Q: How would you structure exception handling in .NET 8?

IExceptionHandler implementations, registered in order, each returning true if it handled the exception and false to pass it down the chain. Specific handlers first — not-found, conflict, validation — and an unconditional catch-all last, because if every handler returns false the exception propagates and you get the default bare 500. Each handler writes through IProblemDetailsService so the shape stays consistent with everything else, and the catch-all is where the logging and the development-versus-production detail decision live.


Traps ⚠️

  • Exception messages in a 500 body leak paths, hostnames and account names.
  • Stack traces in production expose every package version you run.
  • No catch-all IExceptionHandler — if all return false, you get a bare 500.
  • Forgetting UseStatusCodePages leaves routing 404s with an empty body.
  • Handler registration order — a catch-all registered first swallows everything.
  • type changing between releases breaks clients branching on it.
  • Specifics only in the detail prose forces clients to regex English.
  • Cached error responses get served to everyone.
  • Different error shapes per endpoint is the problem this solves — do not reintroduce it.
  • UseExceptionHandler placed after other middleware misses their exceptions.
  • Localising title breaks anything grouping on it. Localise detail instead.


Sources