Skip to content

4. Override ProblemDetails builder

Stratis Dermanoutsos edited this page Sep 18, 2025 · 5 revisions

There is one simple way to override the default ProblemDetails builder - Create your own extending our IRestExceptionProblemDetailsBuilder and register it as Singleton.

For example:

1. Create the builder

Fully custom

public class UserIdProblemDetailsBuilder : IRestExceptionProblemDetailsBuilder
{
    public ProblemDetails Build(HttpContext httpContext, RestException restException)
    {
        var problemDetails = new ProblemDetails
        {
            Status = (int)restException.StatusCode,
            Title = restException.Title,
            Detail = restException.Message,
            Type = $"https://www.rfc-editor.org/rfc/rfc9110.html#name-{restException.TypeSuffix}",
            Extensions = new Dictionary<string, object?> {
                { "userId", httpContext.User.FindFirst("Id")?.Value ?? "-" }
            }
        };

        return problemDetails;
    }
}

Making use of the package's default

public class UserIdProblemDetailsBuilder : IRestExceptionProblemDetailsBuilder
{
    public ProblemDetails Build(HttpContext httpContext, RestException restException)
    {
        // Create default ProblemDetails
        var defaultBuilder = new DefaultRestExceptionProblemDetailsBuilder();
        var problemDetails = defaultBuilder.Build(httpContext, restException);

        // Make modifications
        problemDetails.Extensions.Add("userId", httpContext.User.FindFirst("Id")?.Value ?? "-");

        return problemDetails;
    }
}

References:

2. Register as a service

builder.Services.AddSingleton<IRestExceptionProblemDetailsBuilder, UserIdProblemDetailsBuilder>();

Ideally, do this before registering the middleware itself.

builder.Services.AddRestExceptions();

3. Results

Default

{
    "type": "https://www.rfc-editor.org/rfc/rfc9110.html#name-404-not-found",
    "title": "Not Found",
    "status": 404,
    "detail": "The form was not found.",
    "instance": "/forms/50",
    "traceId": "00-a990b43a04d5860e3e8ec0fb8d8b0f4f-a1993ba072baf468-00",
    "method": "GET",
    "requestId": "0HNEC3JK52NBG:00000001"
}

UserIdProblemDetailsBuilder

{
    "type": "https://www.rfc-editor.org/rfc/rfc9110.html#name-404-not-found",
    "title": "Message in title: The form was not found.",
    "status": 404,
    "detail": "Not Found",
    "instance": "/forms/50",
    "userId": "f038f5d2-2f4c-4e07-88f4-fff8b07045d8",
    "traceId": "00-88963d8c894b42b7041b02f610c400dc-3e914fd68d9137ad-00",
    "method": "GET",
    "requestId": "0HNEC3LDP62CM:00000001"
}

Notes to remember

1. Non-overrideable extension properties

  • "instance"
  • "method"
  • "requestId"
  • "traceId"
Clone this wiki locally