Skip to main content
Version: 2.x

Custom Mappers

The failure-to-status mapping is driven by a single contract, IFailureHttpMapper. The default mapping (see HTTP Mapping) covers the standard failure types, but you can add mappings for your own failure types, override the defaults, or replace the mapper entirely.

using UnambitiousFx.Functional.AspNetCore;
using UnambitiousFx.Functional.AspNetCore.Mappers;

The contract​

public interface IFailureHttpMapper
{
FailureHttpResponse? GetFailureResponse(IFailure failure);
}

A mapper returns a FailureHttpResponse (status code, body, optional headers, optional content type) — or null to signal "I don't handle this failure", letting the next mapper in the chain try.

public sealed record FailureHttpResponse
{
public required int StatusCode { get; init; }
public object? Body { get; init; }
public IReadOnlyDictionary<string, string>? Headers { get; init; }
public string? ContentType { get; init; }
}

Adding mappings via AddResultHttp​

ResultHttpOptions provides three AddMapper overloads. Custom mappers are evaluated before the default mapper, in the order added — the first non-null response wins (chain of responsibility).

Map a failure type to a status code​

The simplest overload maps a failure type to a status code and produces a ProblemDetails body from the failure message:

builder.Services.AddResultHttp(options =>
{
options.AddMapper<RateLimitFailure>(429);
options.AddMapper<TimeoutFailure>(504);
});

Map with a custom response factory​

For full control over the body, headers, and content type, pass a factory:

builder.Services.AddResultHttp(options =>
{
options.AddMapper<PaymentRequiredFailure>(failure => new FailureHttpResponse
{
StatusCode = 402,
Body = new { message = failure.Message },
Headers = new Dictionary<string, string> { ["Retry-After"] = "3600" },
ContentType = "application/json",
});
});

Register an IFailureHttpMapper instance​

builder.Services.AddResultHttp(options =>
{
options.AddMapper(new MyFailureHttpMapper());
});

AddResultHttp resolves the final mapper (a single mapper, or a CompositeFailureHttpMapper wrapping your custom mappers followed by the default) and registers it as a singleton, along with the ResultHttpAdapterPolicy.

Map a failure code to a status code​

Map failures by their Code, for plain Failure(code, message) with domain codes or third-party codes. Code mappings are checked after the type mappers above and before the built-in mapping by failure type. The body stays the one built for the failure type (a ValidationFailure keeps its errors), with the mapped status.

builder.Services.AddResultHttp(options => options
.MapCode("fx.sync_running", 409) // exact code, ordinal
.MapCodePrefix("documents.", 413) // any code starting with "documents."
.DefaultStatus(422) // failures with no mapping, instead of 500
.ExposeMetadata("freeBp", "line")); // copied into ProblemDetails extensions
  • An exact MapCode wins over a prefix; prefixes are tried in the order they are added.
  • DefaultStatus applies to failures with no built-in mapping and no code mapping, such as a plain Failure. Below 500 the response carries the failure message as detail; at 500 and above the message stays hidden unless IncludeExceptionDetails is on.
  • The default mapper always writes the failure code into the ProblemDetails extensions.
  • ExposeMetadata copies only the listed keys of Failure.Metadata, so internal metadata never leaks by default. A key never replaces an extension the mapper already wrote (code, errors, …), and the built-in ProblemDetails members (type, title, status, detail, instance) are rejected with an ArgumentException.
// Failure("fx.sync_running", "A sync is running.") with MapCode("fx.sync_running", 409)
{ "title": "An error occurred.", "status": 409, "detail": "A sync is running.", "code": "fx.sync_running" }

Writing a full custom mapper​

Implement IFailureHttpMapper when you want to map several failure types in one place. Return null for failures you don't handle so the chain can fall through to the default mapper:

using UnambitiousFx.Functional.AspNetCore.Mappers;
using UnambitiousFx.Functional.Failures;

public sealed class MyFailureHttpMapper : IFailureHttpMapper
{
public FailureHttpResponse? GetFailureResponse(IFailure failure) => failure switch
{
NotFoundFailure nf => new FailureHttpResponse { StatusCode = 404, Body = new { nf.Message } },
ValidationFailure vf => new FailureHttpResponse { StatusCode = 422, Body = new { vf.Message } },
_ => null, // let the next mapper / default handle it
};
}
builder.Services.AddResultHttp(options => options.AddMapper(new MyFailureHttpMapper()));

Overriding only a few default mappings​

DefaultFailureHttpMapper.GetFailureResponse is virtual. Subclass it to change specific cases and defer to the base for everything else:

using UnambitiousFx.Functional.AspNetCore.Mappers;
using UnambitiousFx.Functional.Failures;

public sealed class CustomDefaultMapper : DefaultFailureHttpMapper
{
public override FailureHttpResponse GetFailureResponse(IFailure failure)
{
// Map validation errors to 422 instead of the default 400
if (failure is ValidationFailure validation)
{
return new FailureHttpResponse
{
StatusCode = 422,
Body = new { errors = validation.Failures },
};
}

return base.GetFailureResponse(failure);
}
}
builder.Services.AddResultHttp(options => options.AddMapper(new CustomDefaultMapper()));
tip

Because the custom mapper always returns a non-null response for the cases it handles and delegates the rest to base, you don't need to re-declare every failure type.

Per-call mappers​

You don't have to register a mapper globally — pass one directly to a builder for a single endpoint:

await service.GetUserAsync(id).AsHttpBuilder(new MyFailureHttpMapper()); // Minimal API
await service.GetUserAsync(id).AsActionResultBuilder(new MyFailureHttpMapper()); // MVC

When omitted, the builders use the mapper registered by AddResultHttp, or DefaultFailureHttpMapper when none is registered.

Composing mappers manually​

CompositeFailureHttpMapper chains mappers and returns the first non-null response. AddResultHttp builds one for you, but you can compose explicitly:

var mapper = new CompositeFailureHttpMapper(
new MyFailureHttpMapper(),
new DefaultFailureHttpMapper());

Adapter policy​

ResultHttpAdapterPolicy (exposed via options.Policy) tunes default behavior. It is registered as a singleton by AddResultHttp and read by the builders when the response is written:

builder.Services.AddResultHttp(options =>
{
options.IncludeExceptionDetails = builder.Environment.IsDevelopment();
options.Policy = options.Policy with
{
ResultSuccessBehavior = ResultSuccessHttpBehavior.Ok, // NoContent (default) | Ok
MaybeNoneBehavior = MaybeNoneHttpBehavior.NoContent, // NotFound (default) | NoContent
};
});
  • ResultSuccessBehavior — how a successful non-generic Result maps when no explicit success mapper is given (NoContent → 204, Ok → 200).
  • MaybeNoneBehavior — how Maybe.None maps when no AsNone mapper is given (NotFound → 404, NoContent → 204).
  • IncludeExceptionDetails — whether 500 responses from the default mapper include the failure message and, for an ExceptionalFailure, exceptionType and stackTrace extensions. When false (the default), 500 responses carry only title, status and type. Enable only in development.

Composition guidelines​

  • Keep domain failures transport-agnostic; map transport semantics in one place (the composition root).
  • Prefer typed failures over message parsing for deterministic mapping.
  • Reuse the same registered mapper across Minimal APIs and MVC for consistent error shapes.

See also​