Error response design: RFC 9457 ProblemDetails fields and extensions, validation error shape, a stable error-code catalogue, hiding internals with a trace id, and consistency across services and gateways.
I return ProblemDetails (RFC 9457, which replaced RFC 7807 in 2023) with Content-Type: application/problem+json. Its fields are type (a stable URI identifying the error kind), title (a constant summary for that type), status, detail (this occurrence) and instance, plus extensions.
errors map from field to messages.code from a published catalogue, like ORDER_ALREADY_SHIPPED, so clients branch on codes, not message text.traceId and log the detail.Consistency comes from one shared configuration (AddProblemDetails, exception handler) and API guidelines. The trade-off: a code catalogue is a contract you must maintain, but it's what lets clients handle errors reliably.
"Errors are part of the API contract, and clients write more code around errors than around success. So I standardise on ProblemDetails, defined by RFC 9457, which obsoleted RFC 7807 in 2023 but kept it compatible. A problem response has the
application/problem+jsonmedia type and five standard members:type, a URI that identifies the kind of problem and ideally points at documentation;title, a short summary that stays the same for that type;status, mirroring the HTTP status;detail, a human explanation of this occurrence; andinstance, identifying this occurrence. Anything else goes in extension members.On top of that I add two extensions everywhere:
traceId, from the W3C trace context so support can find the request in Application Insights, and a stablecodefrom an error catalogue, likeORDER_ALREADY_SHIPPEDorPAYMENT_DECLINED. Clients switch oncode, never ondetailtext, so we can reword messages or translate them without breaking anybody. Validation failures are a 400 with anerrorsdictionary from field name to messages, which is whatValidationProblemDetailsin ASP.NET Core produces, and field names use the same casing as the JSON body.The mistake I see is leaking internals: returning
ex.Message, a stack trace or a SQL error to the client. That's an information disclosure finding in every penetration test, and under the Privacy Act it can even leak personal data from the failing query. The client gets a generic 500 problem with the trace id; the details go to the logs. The other mistake is inconsistency: each service invents its own shape, so the mobile team writes five error parsers. I fix that once, in a shared package and the API guidelines, not service by service."
| Member | Meaning | Example |
|---|---|---|
type |
URI identifying the problem type; defaults to about:blank |
https://errors.example.com.au/order-already-shipped |
title |
Short summary, constant for the type | Order already shipped |
status |
HTTP status code (advisory copy) | 409 |
detail |
Explanation of this occurrence, for humans | Order 4821 shipped on 18 Nov and can't be cancelled. |
instance |
URI for this occurrence | /v1/orders/4821/cancellation |
| extensions | Anything else | code, traceId, errors, retryAfter |
HTTP/1.1 409 Conflict
Content-Type: application/problem+json
{
"type": "https://errors.example.com.au/order-already-shipped",
"title": "Order already shipped",
"status": 409,
"detail": "Order 4821 shipped on 18 Nov 2026 and can't be cancelled.",
"instance": "/v1/orders/4821/cancellation",
"code": "ORDER_ALREADY_SHIPPED",
"traceId": "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"
}
HTTP/1.1 400 Bad Request
Content-Type: application/problem+json
{
"type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"code": "VALIDATION_FAILED",
"errors": {
"email": ["Email is required."],
"items[0].quantity": ["Quantity must be between 1 and 99."]
},
"traceId": "00-..."
}
| Information | Client response | Server logs |
|---|---|---|
Error kind (type, code) |
Yes | Yes |
Human message (detail) |
Yes, safe text | Yes |
| Trace id | Yes | Yes |
| Exception type, stack trace, SQL | No | Yes |
| Personal data of other users | Never | Only if needed and permitted |
We had [six] services returning four different error shapes; the mobile app had a parser per service and showed "Something went wrong" for most failures. A shared ProblemDetails package with a 40-entry code catalogue let the app map codes to specific messages. Support tickets that said only "error" dropped by [about a third] because users saw actionable text, and every ticket now quoted a trace id.
Checks that the candidate designs errors as a contract: standard format, stable codes, safe content and consistency.
Green flags
application/problem+jsoncode/type from human detailRed flags
RFC 7807 (2016) defined Problem Details. RFC 9457 (July 2023) obsoletes it with small changes: clearer guidance on type URIs, a way to represent multiple problems of the same type in one response, and an IANA registry of common problem types. The JSON format is unchanged, so existing clients keep working. When interviewers say "7807" they mean the same thing.
exception thrown ──► UseExceptionHandler ──► IExceptionHandler(s) ──┐
▼
empty 4xx/5xx ──► UseStatusCodePages ──► IProblemDetailsService ──► writer ─► application/problem+json
▲
Results.Problem / TypedResults.ValidationProblem ──┘
(CustomizeProblemDetails runs for all of them)
AddProblemDetails(o => o.CustomizeProblemDetails = ...) is the one place to add traceId, code defaults or an instance. In development the exception handler can include exception details; in production it must not.
type and codetype is a URI. It doesn't have to resolve, but if it does, put the documentation there: cause, how to fix, whether to retry.title is constant for a type; don't put ids in it.code is a short, stable, SCREAMING_SNAKE identifier. It duplicates the information in type, but clients find a short string easier to switch on, and it survives if your docs domain changes.| code | status | retryable | client action |
|---|---|---|---|
VALIDATION_FAILED |
400 | No | Fix input, show errors |
ORDER_ALREADY_SHIPPED |
409 | No | Offer return instead |
CONCURRENCY_CONFLICT |
412 | After refetch | Reload and reapply |
RATE_LIMITED |
429 | Yes, after Retry-After |
Back off |
DEPENDENCY_UNAVAILABLE |
503 | Yes | Retry with jitter |
The errors member isn't in the RFC; it's an ASP.NET Core convention (ValidationProblemDetails) that has become the de facto standard. Keys should match the JSON path the client sent (items[0].quantity), using the same camelCase as the payload. RFC 9457 also suggests representing several problems of one type as an array in an extension, which is another valid shape; pick one in your guidelines.
Information disclosure (OWASP API Security Top 10 includes security misconfiguration and verbose errors) gives attackers table names, library versions and file paths. Under the Australian Privacy Act, a SQL error echoing a row can disclose personal information. Rules: generic detail for 5xx, specific detail only for errors the client caused and can fix, never echo other users' data, and log the full exception with the same trace id.
AddProblemDetails, the exception handler and the code catalogue types.AddProblemDetails with a CustomizeProblemDetails that adds traceId, throw an exception and inspect the 500 response in Development and Production.errors keys.IExceptionHandler that maps a domain exception to a 409 with a code.Content-Type: application/problem+json.One configuration that makes every error a ProblemDetails with traceId and a stable code, and maps domain errors without leaking internals.
// Program.cs
using System.Diagnostics;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails(o => o.CustomizeProblemDetails = ctx =>
{
// Every problem gets a trace id support can search for in Application Insights.
ctx.ProblemDetails.Extensions["traceId"] =
Activity.Current?.Id ?? ctx.HttpContext.TraceIdentifier;
ctx.ProblemDetails.Instance ??= ctx.HttpContext.Request.Path;
// Default codes for framework-produced problems.
ctx.ProblemDetails.Extensions.TryAdd("code", ctx.ProblemDetails.Status switch
{
400 => "VALIDATION_FAILED",
401 => "UNAUTHENTICATED",
403 => "FORBIDDEN",
404 => "NOT_FOUND",
429 => "RATE_LIMITED",
_ => "INTERNAL_ERROR"
});
});
builder.Services.AddExceptionHandler<DomainExceptionHandler>();
builder.Services.AddValidation(); // .NET 10 Minimal API validation -> ValidationProblem
var app = builder.Build();
app.UseExceptionHandler(); // unhandled exceptions -> problem+json, no stack trace in Production
app.UseStatusCodePages(); // empty 404/405 -> problem+json
app.MapPost("/v1/orders/{id:int}/cancellation", (int id) =>
{
// Simulate a business rule failure.
throw new DomainException("ORDER_ALREADY_SHIPPED", StatusCodes.Status409Conflict,
"Order already shipped", $"Order {id} has shipped and can't be cancelled.");
});
app.Run();
public sealed class DomainException(string code, int status, string title, string detail)
: Exception(detail)
{
public string Code { get; } = code;
public int Status { get; } = status;
public string Title { get; } = title;
}
// Maps known business errors; anything else falls through to a generic 500.
public sealed class DomainExceptionHandler(IProblemDetailsService problems) : IExceptionHandler
{
public async ValueTask<bool> TryHandleAsync(HttpContext http, Exception exception, CancellationToken ct)
{
if (exception is not DomainException e) return false;
http.Response.StatusCode = e.Status;
return await problems.TryWriteAsync(new ProblemDetailsContext
{
HttpContext = http,
Exception = exception,
ProblemDetails = new ProblemDetails
{
Type = $"https://errors.example.com.au/{e.Code.ToLowerInvariant().Replace('_', '-')}",
Title = e.Title, // constant per type
Status = e.Status,
Detail = e.Message, // safe, client-actionable text only
Extensions = { ["code"] = e.Code }
}
});
}
}
{ "success": false }. Why it is wrong: Clients, gateways, retries and monitoring all rely on the status code. Instead: Use the correct 4xx/5xx with a ProblemDetails body.ex.Message or a stack trace in detail. Why it is wrong: It leaks internals and sometimes personal data, and fails penetration tests. Instead: Generic text for 5xx, log the exception, return a traceId.detail or title text. Why it is wrong: Any rewording or translation breaks them. Instead: Publish stable code values and type URIs to switch on.title. Why it is wrong: RFC 9457 says title is constant per type; it breaks grouping in dashboards. Instead: Variable details go in detail or extensions.Results.Json(...), which sends application/json. Why it is wrong: Clients and tools can't tell an error document from a resource. Instead: Always send application/problem+json by letting IProblemDetailsService (or Results.Problem) write the response.items[0].quantity.The error catalogue is the part most teams skip and most clients need. A status code tells a client which family of thing went wrong; a stable code tells it what to do. I keep the catalogue small, add a code only when a client would act differently on it, and document retryability next to each one, because that's what drives client resilience logic.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
Plain ProblemDetails, type only |
Small internal APIs | Clients compare URIs | Many clients and many error kinds |
ProblemDetails + code catalogue |
Public, partner and mobile APIs | Catalogue governance | Prototypes |
Custom envelope ({ error: { code, message } }) |
Legacy clients already depend on it | Non-standard; tooling doesn't understand it | New APIs |
Localised detail via Accept-Language |
Consumer apps showing server text | Translation workflow | When clients map codes to their own text anyway |
I measure error quality by how many support tickets include a trace id and by the share of 4xx responses with a specific code rather than a generic one.
ProblemDetails is the standard JSON shape for HTTP API errors, defined by RFC 9457 (which replaced RFC 7807): type, title, status, detail, instance, plus extension members, served as application/problem+json. ValidationProblemDetails adds an errors dictionary per field. In ASP.NET Core, AddProblemDetails() registers IProblemDetailsService, which the framework uses wherever it writes an error body: UseExceptionHandler for unhandled exceptions, UseStatusCodePages for empty 404s/401s, and the developer exception page. CustomizeProblemDetails adds a traceId and anything else to every response; an IExceptionHandler maps known exceptions to specific codes with a stable errorCode extension. The trade-off: one consistent contract for every error, but you must make sure no internal detail leaks.
The status code tells clients and infrastructure what happened before they read the body, so it must be exact.
200 OK with a body, 201 Created plus a Location header, 202 Accepted for work that finishes later, 204 No Content when there's nothing to return.400 bad input, 422 well-formed but semantically invalid, 401 not authenticated vs 403 not allowed, 404 not found vs 410 gone, 409 conflicts with current state, 412 a precondition like If-Match failed, 429 rate limited with Retry-After.500 our bug, 502 bad upstream response, 503 temporarily unavailable, 504 upstream timeout.The trade-off is precision versus consistency: pick a small, documented set and use it the same way in every service.
I validate input at the edge and business rules in the application or domain layer. For input, DataAnnotations ([Required], [Range], [StringLength]) and IValidatableObject on request DTOs are the baseline. In controllers, binding fills ModelState and [ApiController] returns a 400 ValidationProblemDetails before the action runs. In Minimal APIs on .NET 10, builder.Services.AddValidation() uses a source generator to validate parameters and return the same 400 ProblemDetails; before .NET 10 you needed a filter. FluentValidation is my choice for complex, conditional or async rules; I call it explicitly or from a filter, because its automatic MVC integration is deprecated. Business rules like stock levels or uniqueness are checked where the data lives and returned in the same error shape. The trade-off: attributes are simple and visible in OpenAPI; code-based validators are more expressive.
Last updated 23 Nov 2026.