ADR-0024: Problem details v2 — one shape, one writer, a stable code on every problem
- Status: accepted
- Date: 2026-10-08
- Supersedes: the "At the HTTP boundary…" paragraph of ADR-0004 (the Result decision itself stands).
- Refines: ADR-0021 (the 401/403/429 writers it introduced now go through the problem-details service).
- Amended: 2026-10-11 —
Result.Combinemerges only validation failures; a handler names the request field of a value-object or aggregate-rule error (AtField); aResultnever reaches JSON (see Amendment below) - Amended: 2026-10-11 — every 5xx
detailis the catalogue sentence; the 503 and 412 titles; the field of a body value of the wrong type;WWW-Authenticateon every 401; two more idempotency outcomes (see Second amendment below); and a correction to rule 5: an uncodedMustarrives asValidation.Predicate, notValidation.Invalid, so the validator convention test refuses it - Amended: 2026-11-10 —
Request.InvalidValuecarries one of two fixed sentences: the wrong-type one, or the NUL one for a body string holding U+0000 (see Amendment (2026-11-10) below)
Context
Section titled “Context”The first error contract mapped Result failures to RFC 9457 at one seam (CustomResults.Problem,
ADR-0004) but left the document itself half-specified, and the audit found six consequences:
titlewas the machine code ("Invoice.NotFound") andtypeASP.NET's generic RFC 9110 link; there was nocodemember, so clients branched ontitleor onstatusalone.- A 400 carried
errors: [{code, description}]wherecodewas FluentValidation'sPropertyName("CustomerName") for validator failures and a real code ("EmailAddress.Invalid") for domain errors; a single domain validation error had noerrors[]at all. - 401, 403 and 429 were hand-written with
WriteAsJsonAsync: notype, notraceId, and theCustomizeProblemDetailshook never ran for them. An unknown route's 404, a 405 and a 415 had no body. - Malformed JSON, a missing body or
/invoices/not-a-guidsurfaced asBadHttpRequestException, which the catch-all handler turned into a 500 "Server failure" in Development (where every in-process test runs) and the framework into a bodyless 400 everywhere else. - Three title conventions coexisted; the idempotency filter built its own
TypedResults.Problemtwice. - Nothing carried the correlation id, so a support engineer holding a problem body could not find the log lines without the response headers.
Decision
Section titled “Decision”The wire contract
Section titled “The wire contract”Every response with status ≥ 400 is application/problem+json with this shape (★ = added here):
{ "type": "urn:problem-type:Validation.General", ★ always ours, never the RFC 9110 link "title": "Validation failed", ★ human, fixed per error class "status": 400, "detail": "One or more validation errors occurred.", "instance": "/api/v1/invoices", ★ the request path "code": "Validation.General", ★ machine discriminator == Error.Code "correlationId": "01JB8Z5M9K-trace.id:42", ★ == the X-Correlation-ID response header "traceId": "00-dc43cf54…-01", (ASP.NET's defaults) "errors": [ ★ on every 400 produced from a Result; absent otherwise { "field": "customerName", "code": "Validation.NotEmpty", "description": "'Customer Name' must not be empty." }, { "field": null, "code": "Invoice.NoLines", "description": "An invoice needs at least one line before it can be issued." } ]}codefollowsArea.Problem— PascalCase both sides, exactly one dot (Invoice.NotFound,Auth.InvalidCredentials,Validation.NotEmpty,Request.Malformed). Codes are what clients switch on; they never change meaning once shipped. A problem never omitscode.typeis"urn:problem-type:" + code: one spelling of each identifier acrosscode,type, logs and docs, and a URN because nothing is served at it (RFC 9457 §4 allows exactly that). The prefix is one constant (ProblemTypes.Prefix) a product changes to a documentation URL if it publishes one.titleis a short human phrase per error class, no trailing period: Validation → "Validation failed", NotFound → "Not found", Conflict → "Conflict", Unauthorized → "Unauthorized", Forbidden → "Forbidden", Failure → "Server failure"; the non-Result rows use the catalogue titles below. Titles are for people, not for branching. (Amended 2026-10-11: Unavailable → "Service unavailable", PreconditionFailed → "Precondition failed"; see the second amendment below.)detailisError.Descriptionor the catalogue sentence. Exception messages never reachdetailexcept the framework's ownBadHttpRequestException.Message, which names a parameter or a limit, not a stack. The 500's detail is always "An unexpected error occurred." (Reworded by the second 2026-10-11 amendment below: a 4xx carriesError.Description; every 5xx, a Result-produced one included, carries the catalogue sentence and keeps itscode.)errors[]appears on every 400 produced from aResult(CustomResults.ProblemwithErrorType.Validation), never elsewhere (amended 2026-10-11: and on a 400 whose body held a value of the wrong type; see the second amendment below):fieldis the JSON path of the offending request member (customerName,lines[0].amount: camelCase per segment, computed at the API seam from FluentValidation'sPropertyName), ornullwhen the error is about the request as a whole (every domain value-object error). (Superseded by the 2026-10-11 amendment below: a handler names the field of a value-object or aggregate-rule error withAtField;nullremains for an error about the request as a whole, such asInvoice.NoLines.)codeper entry: a FluentValidation failure isValidation.+ the validator name without itsValidatorsuffix (Validation.NotEmpty,Validation.MaximumLength,Validation.Email); a rule with.WithErrorCode("Invoice.DueDateInPast")passes its code through; a failure with no code isValidation.Invalid. A domain error keeps its own code. (Corrected 2026-10-11: an uncodedMustis not a failure with no code. FluentValidation names it after its predicate validator, so it arrives asValidation.Predicate, orValidation.AsyncPredicateforMustAsync, a code no client can branch on;CommandValidatorConventionTeststherefore fails anyMustorMustAsyncwithout.WithErrorCode(...).Validation.Invalidis what a failure with an empty code gets, such as aCustomrule'sAddFailure.)- A 400 from a single plain validation error (
Invoice.NoLines) still carrieserrors: [{ field: null, code: "Invoice.NoLines", … }]with top-levelcode: "Invoice.NoLines"; aValidationErrorcarries top-levelcode: "Validation.General"and the list. Clients can therefore always rendererrors[]on a 400 and never special-case.
correlationIdequals theX-Correlation-IDresponse header — the inbound value when the caller sent a safe one, else the request's W3C trace id.CorrelationIdMiddlewarekeeps the id inHttpContext.Itemsfor the enrichment and re-asserts the header when the response starts, because the exception-handler middleware clears the response before it writes the 500.
Rejected alternative: ASP.NET's HttpValidationProblemDetails (errors: { "customerName": ["…"] }).
It is what TypedResults.ValidationProblem emits, but it drops the per-entry code a localising client
needs and cannot express whole-request errors; the array keeps the shipped member name and is stated
explicitly in the OpenAPI document (ADR-0025), so generators do not guess.
In SharedKernel
Section titled “In SharedKernel”FieldError(Field, Code, Description) : Error is what ValidationDecorators emits per FluentValidation
failure (it replaces the internal FieldValidationFailure of the pipeline-v2 pass); domain errors stay
plain Errors; ValidationError aggregates both and Result.Combine flattens nested ones unchanged.
The outcome log line's field:code pairs read the same record. (Refined by the 2026-10-11 amendment
below: Combine merges only when every failure is a validation error.)
One writer, one catalogue (Api.Common)
Section titled “One writer, one catalogue (Api.Common)”CustomResults.Problem(Error)is the only Result → HTTP translation (unchanged signature).ProblemCatalogholds every situation that does not come from a Result, one row each:Auth.Unauthenticated(401),Auth.Forbidden(403),RateLimit.Exceeded(429),Request.Malformed(400),Request.TooLarge(413),Request.UnsupportedMediaType(415),Server.Failure(500). The catalogue does not carryConcurrency.Conflict: the unit of work returns it as a Result (UnitOfWorkErrors.ConcurrencyConflict) and the Result path maps it. The idempotency filter's outcomes areIdempotencyErrors(Idempotency.InvalidKey400,Idempotency.InFlightandIdempotency.Duplicate409 — the type lives inTrellis.Application.Abstractionssince the ADR-0018 amendment, because Persistence producesDuplicate) written throughCustomResults, like any endpoint's; the 422Idempotency.FingerprintMismatchhas noErrorType, so it is aProblemDescriptorwritten throughWriteProblemAsync.HttpContext.WriteProblemAsync(ProblemDescriptor)is how a non-Result path writes: throughIProblemDetailsService. The JWT challenge (keepingWWW-Authenticate), the forbidden callback, the rate limiter's rejection (keepingRetry-After) and both exception handlers use it. Nothing writes a problem withTypedResults.ProblemorWriteAsJsonAsyncdirectly.AddProblemDetails(CustomizeProblemDetails)inAddApiCommonis the single enrichment point: it fillsinstance, overwritestypewith the URN, derivesHttp.{ReasonPhrase}(and the catalogue's 413/415 rows) for a problem nobody authored, and addscorrelationId.app.UseStatusCodePages()gives every response that would leave with a status and no body a problem document: an unknown route's 404 (Http.NotFound), a 405 (Http.MethodNotAllowed,Allowkept), the request-timeout 504, Kestrel's 413. Responses that already wrote a body are untouched.RouteHandlerOptions.ThrowOnBadRequest = truein every environment, andBadHttpRequestExceptionHandler(registered before the catch-all) answers the exception's own status as a problem and logs at Information: a malformed request is a client error, not an incident. The exception-handler middleware's default already suppresses its Error log anderror.typemetric for an exception anIExceptionHandlerhandled, so no diagnostics callback is configured.
The client mirror
Section titled “The client mirror”Api.Contracts.Common.ProblemResponse and FieldError are the wire shape as records: tolerant readers
(every member nullable) that the UI deserialises and the OpenAPI document generates its problem schema
from (ADR-0025). Trellis.Api.Common therefore references Trellis.Api.Contracts — a BCL-only leaf, so
the dependency still points inward: Api → Api.Common → Api.Contracts ← UI.Common.
LayerDependencyTests pins the direction (Contracts never references Common).
What consumers may rely on
Section titled “What consumers may rely on”- The status,
code,type == "urn:problem-type:" + code,instance,traceId,correlationId, and — on a 400 produced from a Result —errors[].field(a JSON path or null),errors[].code. detailanderrors[].descriptionare safe to show to a user on a 4xx; a 5xx carries nothing specific by design.- Not the wording of
titleordetail: both are for people and may be rephrased or localised without a version bump. Branch oncode.
ProblemDetailsContractTests proves every row of this contract through the real pipeline, one status at
a time, by deserialising each response into ProblemResponse.
Consequences
Section titled “Consequences”- Adding an error means adding a code to an
*Errorsclass — nothing changes in the API; a new non-Result situation gets aProblemCatalogrow and is written withWriteProblemAsync. FieldError.Fieldis a request JSON path on the wire, so a Blazor form can feederrors[]straight into aValidationMessageStorekeyed by field (the UI follow-up), and an API client can highlight the offending input without parsing messages.- A support engineer holding either the body or the headers of a failed call has the correlation id and the trace id; the two always agree.
- Malformed input no longer produces Error-level log lines or a 500 count, and the shipped behaviour is identical in Development and Production — the in-process tests prove what production does.
- The
typeURN is not dereferenceable. A product that wants documentation links changesProblemTypes.Prefixonce; every consumer that branched oncodeis unaffected.
Amendment (2026-10-11): Result.Combine merges only validation failures; value-object errors name their field; a Result never reaches JSON
Section titled “Amendment (2026-10-11): Result.Combine merges only validation failures; value-object errors name their field; a Result never reaches JSON”Combine is type-aware. As first written, Result.Combine flattened any two failures into one
Validation.General, so two NotFounds, or a NotFound beside a Failure, answered 400 and logged at
Information. It now merges into a ValidationError only when every failure is ErrorType.Validation
(nested ones still flattened); otherwise it returns one error unmerged: the first Failure, else the
first non-validation failure. The validation errors beside it are dropped, because the 404 or the 500 is
the answer that matters. A single failure is returned as it is. Combine<T1, T2> and Combine<T1, T2, T3> apply the same rule
and keep the values as a tuple, which the deconstructing Bind/Map overloads unpack, so
CreateInvoiceCommandHandler is one chain. The wire contract above is unchanged.
Value-object and aggregate-rule errors name the request field. Rule 5 made every domain
value-object error a whole-request error, so an API client or the Blazor form could not put
"The email address is not in a valid format." under the e-mail input when "a@b" passed every shape
check and only EmailAddress.Create rejected it. The Domain stays transport-free: factories and
aggregate methods still return plain Errors. The handler, which knows which request member it passed,
attributes the failure with Result.AtField(member) (in ResultExtensions):
EmailAddress.Create(command.CustomerEmail).AtField(nameof(command.CustomerEmail)). AtField rewraps
a plain ErrorType.Validation error as FieldError(member, code, description). It passes through every
other type, an existing FieldError and an aggregated ValidationError, so each value object is
attributed before Combine. The code-selective overload, AtField(member, params Error[] only), serves a
value object spanning two inputs or an aggregate method with several rules: Invoice.Issue attributes
Invoice.DueDateInPast to dueDate while Invoice.NoLines stays field: null. The shape of errors[]
is unchanged and so is every code; only which entries carry a path changed. A client that read
field: null as "a domain error" branches on code instead, as "What consumers may rely on" already says.
ProblemDetailsContractTests pins both kinds.
A Result never reaches JSON. CustomResults.Problem is the only translation, but nothing enforced
it: an endpoint that returned Task<Result<T>> instead of mapping it compiled, passed every gate and
answered 200 with the Result's own members on success and a 500 on failure. Both Result types now carry
[JsonConverter(typeof(ResultJsonGuard))], a converter factory that throws NotSupportedException
naming TypedResults and CustomResults.Problem instead of serialising. Minimal APIs resolve the
response contract when they build the endpoint, so such an endpoint stops the host at boot, and every
in-process test with it; ProblemDetailsContractTests proves it with a throwaway endpoint.
Second amendment (2026-10-11): the HTTP contract, second pass
Section titled “Second amendment (2026-10-11): the HTTP contract, second pass”Every 5xx detail is the catalogue sentence. Rule 4 promised that the 500's detail is always "An
unexpected error occurred.", but CustomResults.Problem copied Error.Description whatever the
status, so a Failure Result put its own text on the wire: the place a third party's answer or a
connection's complaint would land. The seam now computes the status first and, for any status of 500
or more, writes ProblemCatalog.ServerFailure.Detail instead of the description. The code stays, so
the failure is still identifiable from the body, the logs (ADR-0028) and the span. Rule 4 therefore
reads: a 4xx carries Error.Description or the catalogue sentence; a 5xx carries nothing specific,
whichever writer produced it. ProblemDetailsContractTests pins it with a Result-produced 500 whose
description is a secret.
A 503 for a dependency that is down. ADR-0004's amendment adds ErrorType.Unavailable;
CustomResults.Problem maps it to 503 with the title "Service unavailable" (ProblemTitles, and the
same title for a bodyless 503 the status-code pages complete) and the fixed detail "A service this
request depends on is unavailable right now. Retry later." (CustomResults.UnavailableDetail): like
every 5xx it never carries the description, and the code names the dependency
(ExchangeRate.Unavailable). ProblemDetailsContractTests has the 503 row.
A body value of the wrong type names its field. A body that parsed as JSON but did not bind
("amount": "abc", "dueDate": "tomorrow") was a 400 Request.Malformed with the framework's
parameter-level sentence and no field, so neither a form nor an API client could point at the input.
ProblemCatalog.Malformed now reads the serializer's JsonException.Path ($.lines[1].amount) and,
for a conversion failure, adds errors: [{ field: "lines[1].amount", code: "Request.InvalidValue", description: "The value is not of the type this field expects." }]. The field is camel-cased like
every other (the binder matches names case-insensitively); the description is fixed, because the
serializer's own message names CLR types and is never echoed; the top-level code stays
Request.Malformed. A syntax error ({ not json, a stray comma) names no field: the serializer
reports where it stopped reading, often a parent, so the inner reader exception rules it out. Rule 5
and What consumers may rely on therefore read: errors[] is on every Result-produced 400 and on a
400 naming a body value of the wrong type. ProblemDescriptor gained an optional Errors, which
WriteProblemAsync writes as the same extension.
Every 401 carries WWW-Authenticate. The enrichment adds WWW-Authenticate: Bearer to a 401
whose writer set none, so the 401s a Result produces (login's Auth.InvalidCredentials, refresh's
Auth.InvalidRefreshToken) name the scheme as the challenge's always did (ADR-0021 decision 4).
Two idempotency outcomes. A repeated Idempotency-Key header or a comma-separated list used to be
joined into one key the caller never sent; it is now a 400 Idempotency.InvalidKey (the code the blank
and the too-long key share, since the remedy is the same). An endpoint that declares
RequireIdempotency(keyRequired: true) answers a request without the header with a 400
Idempotency.KeyRequired; CreateInvoice is the one that does, because an accidental repeat of a
create cannot be told from a second intent. Both are Results (IdempotencyHeaderErrors, beside the
filter, since nothing below the API produces them; amended 2026-10-11: folded into Application's
IdempotencyErrors, one owner per code, see ADR-0018's second amendment) written through CustomResults
like the rest of the filter's outcomes. ProblemDetailsContractTests has a row for each new code.
A 412 for a stale If-Match. ADR-0004's amendment adds ErrorType.PreconditionFailed;
CustomResults.Problem maps it to 412 with the title "Precondition failed" and, as a 4xx, the error's
own description (Invoice.VersionMismatch: reload and try again). ProblemDetailsContractTests has the
412 row.
Amendment (2026-11-10): Request.InvalidValue carries one of two fixed sentences
Section titled “Amendment (2026-11-10): Request.InvalidValue carries one of two fixed sentences”A body string holding U+0000 is named like a value of the wrong type. PostgreSQL's text stores no
NUL, so a body string holding one reached the first query or save that carried it and answered a 500.
NulFreeStringJsonConverter, registered by AddApiCommon beside the strongly-typed-id converter, now
refuses it while the body binds, and ProblemCatalog.Malformed answers it the way the second amendment
answers a value of the wrong type: a 400 Request.Malformed whose errors[] holds one
Request.InvalidValue entry naming the member by the serializer's path (customerName, email).
The entry's description is one of two fixed sentences, never the serializer's message. The second
amendment made it one fixed sentence; it is now "The value is not of the type this field expects." for a
conversion failure, or ProblemCatalog.NulCharacterDescription ("The value holds a NUL character
(U+0000), which this field does not accept.") for a string the converter refused, chosen by the
exception's type (NulCharacterException), never by its text. No code changes: the top level stays
Request.Malformed and the entry Request.InvalidValue, so a client that branches on code, as What
consumers may rely on says it should, handles a NUL with no change, and the sentence is for people.
Rule 5 and What consumers may rely on therefore read: errors[] is on every Result-produced 400 and on a
400 naming a body value of the wrong type or a body string holding U+0000.
ProblemDetailsContractTests.A_NUL_character_in_a_body_string_is_a_400_that_names_the_field is the row:
a NUL in each string of the create, in a line's description and in sign-in's e-mail, each a 400 naming
its member with Request.InvalidValue and the NUL sentence.
The documentation of Trellis.Templates 0.2.0 · release notes