Atya.Errors.ProblemDetails
2.0.0
Prefix Reserved
dotnet add package Atya.Errors.ProblemDetails --version 2.0.0
NuGet\Install-Package Atya.Errors.ProblemDetails -Version 2.0.0
<PackageReference Include="Atya.Errors.ProblemDetails" Version="2.0.0" />
<PackageVersion Include="Atya.Errors.ProblemDetails" Version="2.0.0" />
<PackageReference Include="Atya.Errors.ProblemDetails" />
paket add Atya.Errors.ProblemDetails --version 2.0.0
#r "nuget: Atya.Errors.ProblemDetails, 2.0.0"
#:package Atya.Errors.ProblemDetails@2.0.0
#addin nuget:?package=Atya.Errors.ProblemDetails&version=2.0.0
#tool nuget:?package=Atya.Errors.ProblemDetails&version=2.0.0
Atya.Errors.ProblemDetails
Atya.Errors.ProblemDetails adds RFC 9457-style ASP.NET Core problem details
responses for the exception types in Atya.Errors.Exceptions and failed
Result values from Atya.Foundation.Results.
It is intended for API boundaries where production services need consistent HTTP status codes, stable problem type identifiers, trace/correlation metadata, and safe handling of unexpected exceptions.
Install
dotnet add package Atya.Errors.ProblemDetails
Compatibility
- Targets
net10.0. - Requires ASP.NET Core through the
Microsoft.AspNetCore.Appframework reference. - Depends on
Atya.Errors.Exceptions,Atya.Foundation.Guards, andAtya.Foundation.Results.
Quick Start
Register the services and add the exception handler middleware early in the pipeline.
using Atya.Errors.ProblemDetails.Extensions;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAtyaProblemDetails();
var app = builder.Build();
app.UseAtyaProblemDetails();
app.MapGet("/customers/{id}", (Guid id) =>
{
throw new Atya.Errors.Exceptions.NotFoundException(
$"Customer '{id}' was not found.",
"customers.not_found");
});
app.Run();
The response is written as application/problem+json and includes the standard
problem details members plus Atya extension members when available.
{
"type": "urn:atya:problem-type:not-found",
"title": "Not Found",
"status": 404,
"detail": "Customer '...' was not found.",
"instance": "/customers/...",
"traceId": "...",
"errorCode": "customers.not_found"
}
Default Mappings
| Exception | Status | Title | Type |
|---|---|---|---|
ValidationException |
400 | Bad Request |
urn:atya:problem-type:validation |
BusinessRuleViolationException |
422 | Unprocessable Entity |
urn:atya:problem-type:business-rule-violation |
UnauthorizedException |
401 | Unauthorized |
urn:atya:problem-type:unauthorized |
ForbiddenException |
403 | Forbidden |
urn:atya:problem-type:forbidden |
NotFoundException |
404 | Not Found |
urn:atya:problem-type:not-found |
ConflictException |
409 | Conflict |
urn:atya:problem-type:conflict |
ConcurrencyException |
409 | Conflict |
urn:atya:problem-type:concurrency-conflict |
InfrastructureException |
500 | Internal Server Error |
urn:atya:problem-type:infrastructure-failure |
| unhandled exceptions | 500 | Internal Server Error |
urn:atya:problem-type:internal-server-error |
Derived exception types use the first assignable mapping when an exact mapping is not configured.
Extension Members
| Extension | Included when |
|---|---|
traceId |
IncludeTraceId is true. The value is the 32-character W3C trace id of Activity.Current (no 00- prefix, span id or flags); without a W3C activity it is HttpContext.TraceIdentifier. A hierarchical Activity.Id is never emitted. |
correlationId |
CorrelationIdAccessor returns a non-empty value. The default returns null: Atya.Web.Middleware wires the accessor to the validated correlation id; used alone, set it yourself. |
errorCode |
IncludeErrorCode is true and the exception has an Atya error code. |
metadata |
IncludeExceptionMetadata is true and the exception has metadata. |
errors |
The exception is an Atya.Errors.Exceptions.ValidationException, or a mapped Results error has Kind = Validation on itself or any child detail. |
Validation errors use this shape:
{
"propertyName": "Email",
"message": "Email is required.",
"errorCode": "validation.required"
}
Attempted values are omitted by default because they can contain sensitive user input.
Failed Results validation errors use an object keyed by Error.Target. Multiple
errors for the same target are preserved in order. A targetless validation error
uses an empty-string key.
{
"Email": [
{
"propertyName": "Email",
"message": "Email is required.",
"errorCode": "validation.required"
}
]
}
Results Mapping
IResultToProblemDetailsMapper maps failed Result, failed Result<TValue>,
or an Error directly to Microsoft.AspNetCore.Mvc.ProblemDetails. Successful
results are not errors and throw InvalidOperationException when passed to the
mapper.
using Atya.Errors.ProblemDetails.Abstractions;
using Atya.Foundation.Results;
app.MapGet("/customers/{id}", (
Guid id,
HttpContext httpContext,
IResultToProblemDetailsMapper mapper) =>
{
Result result = Result.Failure(new Error(
"customers.not_found",
$"Customer '{id}' was not found.",
ErrorKind.NotFound));
return result.IsSuccess
? Results.NoContent()
: Results.Problem(mapper.Map(result, httpContext));
});
Default Results error-kind mappings are:
| ErrorKind | Status | Title | Type |
|---|---|---|---|
Validation |
400 | Bad Request |
urn:atya:problem-type:validation |
Failure |
422 | Unprocessable Entity |
urn:atya:problem-type:failure |
NotFound |
404 | Not Found |
urn:atya:problem-type:not-found |
Conflict |
409 | Conflict |
urn:atya:problem-type:conflict |
Unauthorized |
401 | Unauthorized |
urn:atya:problem-type:unauthorized |
Forbidden |
403 | Forbidden |
urn:atya:problem-type:forbidden |
Unexpected |
500 | Internal Server Error |
urn:atya:problem-type:internal-server-error |
ErrorKind.Failure maps to 422 by default because it represents an expected
operation failure for a syntactically valid request that the service understood
but could not process as requested. Use MapError when a service needs a
different public contract for its own failure category.
Result details and 5xx security
Result errors mapped to statuses from 500 through 599 use the same secure-detail
policy as exception errors. By default, detail is An unexpected error occurred. and error-derived extensions such as the error code and nested
validation errors are omitted. Trace and correlation identifiers remain
available because they are generated by the request pipeline rather than copied
from the error.
Non-5xx mappings retain their existing behavior: the error message is used as
detail, and configured error-code and validation extensions are emitted.
An application may intentionally disclose one reviewed Result detail by using a
MapError detail factory. The factory controls only detail; error-derived
extensions remain redacted for 5xx responses.
builder.Services.AddAtyaProblemDetails(options =>
{
options.MapError(
ErrorKind.Unexpected,
StatusCodes.Status500InternalServerError,
"Internal Server Error",
"urn:example:problem-type:internal-server-error",
static (error, _) => error.Message); // Review before enabling.
});
This is a behavioral compatibility change from version 1.1.0 and earlier,
which could copy Result error content into a 5xx response. Migration normally
requires no code change. If a client has an approved dependency on a public 5xx
detail, configure a narrow MapError factory that returns only that documented
content. To roll back before publication, revert the isolated policy change. To
restore a reviewed legacy detail after publication, use the explicit mapping
above while preparing a forward package update; published packages and tags
must not be rewritten.
Configuration
builder.Services.AddAtyaProblemDetails(options =>
{
options.IncludeExceptionMetadata = true;
options.IncludeTraceId = true;
options.IncludeValidationAttemptedValues = false;
options.CorrelationIdAccessor = httpContext =>
httpContext.Request.Headers.TryGetValue("X-Request-ID", out var values)
? values.ToString()
: null;
options.Map<TimeoutException>(
StatusCodes.Status504GatewayTimeout,
"Gateway Timeout",
"urn:atya:problem-type:gateway-timeout",
static (_, _) => "The upstream service did not respond in time.");
// Remap the default ErrorKind.Failure contract for this service.
options.MapError(
ErrorKind.Failure,
StatusCodes.Status400BadRequest,
"Bad Request",
"urn:example:problem-type:invalid-command");
options.ExtensionNames.Errors = "validationErrors";
options.ExtensionNames.Metadata = null;
// Runs for exceptions and for failed Results, after the Atya extensions are added.
// context.Exception is set on the exception path, context.Error on the result path.
options.Customize = context =>
{
context.ProblemDetails.Extensions["service"] = "orders-api";
};
});
Map<TException> replaces an existing mapping for the same exception type,
trims the title and type values, and rejects HTTP status codes outside the
standard 100 through 599 range. At host start every mapped status must be
400 through 599 unless AllowNonErrorStatusCodes is set, and extension
names must be distinct and must not be RFC 9457 members (type, title,
status, detail, instance); a null extension name disables that extension.
Mappers snapshot the options when they are constructed, so later changes to the
options object do not affect them. When several exception mappings apply, the most
specific (deepest) type wins, independent of registration order. RemoveMapping<TException>() removes one
mapping, and ClearMappings() lets a service fully own its public error
contract.
Exception Details
Unhandled exceptions and mapped 500-level exceptions are deliberately sanitized by default:
{
"status": 500,
"title": "Internal Server Error",
"detail": "An unexpected error occurred."
}
Only enable raw exception details for trusted environments.
builder.Services.AddAtyaProblemDetails(options =>
{
options.IncludeExceptionDetailsPredicate = (httpContext, exception) =>
builder.Environment.IsDevelopment();
});
Known Atya exceptions below status 500 use their exception message as detail.
For mapped 500-level exceptions, use a safe Map<TException> detail factory
when a public detail is useful.
Versioning
Stable packages use SemVer and are produced from vMAJOR.MINOR.PATCH tags.
Problem type URIs, extension names, public types, and serialized JSON member
names are treated as compatibility contracts.
Support
Report issues through the repository at https://github.com/AtyaLibraries/ProblemDetails. Include the package version, target framework, ASP.NET Core version, and a minimal reproduction whenever possible.
Migration from 1.x
DefaultExceptionToProblemDetailsMapperandDefaultResultToProblemDetailsMapperhave one public constructor (IOptions<AtyaProblemDetailsOptions>). UseCreate(AtyaProblemDetailsOptions)for tests and manual composition. Registering both the concrete options type andIOptions<>no longer breaks DI.traceIdis now the 32-hex W3C trace id instead of the fulltraceparentvalue (wire-visible).- The default
CorrelationIdAccessorno longer readsX-Correlation-ID; useAtya.Web.Middlewareor set the accessor. Customize(new) runs on both paths;CustomizeProblemDetailsis obsolete and runs on the exception path only.- New default rows:
ErrorKind.TooManyRequests429,ErrorKind.Unavailable503 andErrorKind.Timeout504 (503/504 detail and error code are masked like other 5xx). NoRetry-Afteris emitted. - Requires
Atya.Foundation.Results1.2.0. BecauseErrorKindgained values, exhaustiveswitchexpressions over it in consumer code need new arms. - Mapped status codes outside 400-599 fail startup unless
AllowNonErrorStatusCodesis set; mapping outcomes can change for apps that depended on registration order.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- Atya.Errors.Exceptions (>= 1.0.0)
- Atya.Foundation.Guards (>= 1.1.0)
- Atya.Foundation.Results (>= 1.2.0)
NuGet packages (1)
Showing the top 1 NuGet packages that depend on Atya.Errors.ProblemDetails:
| Package | Downloads |
|---|---|
|
Atya.Web.Middleware
ASP.NET Core middleware that maps Atya exceptions and results to RFC 9457 ProblemDetails at the HTTP edge. |
GitHub repositories
This package is not used by any popular GitHub repositories.