Catalog My learning Blog
Full-Stack Developer Course: React, .NET and SQL Server · Phase 2 · Lesson 16 · 6 min read

ASP.NET Core Error Handling with ProblemDetails

On this page
  1. Learning Objective
  2. Concept Explanation
  3. Worked Example: A Global Handler That Maps Domain Errors and Hides the Rest
  4. Real-World Examples
  5. Review Questions & Answers

Learning Objective

Build a single global error path that converts exceptions into standard ProblemDetails responses, map domain failures to the right HTTP status codes, include a trace identifier for support without leaking internals, and explain why uniform error responses are also a security control.

Concept Explanation

A frontend developer meets errors as rejected promises and thrown exceptions in one tab. An API has a different job: every failure, from a validation mistake to a crashed dependency, must be turned into an HTTP response that a client can understand and that reveals nothing an attacker can use. Doing that in each endpoint with its own try and catch produces inconsistent responses and forgotten cases. The better design has one central place that catches anything unhandled, logs it in full, and writes a safe, standardized body. In ASP.NET Core that place is the exception handling middleware, and since .NET 8 you customize it by implementing the IExceptionHandler interface.

The standard body format is ProblemDetails, defined in RFC 7807 in 2016 and revised by RFC 9457 in 2023. It is a small JSON object with a type URI identifying the kind of problem, a short title, the HTTP status, an optional detail, and an instance. You may add extension members such as a traceId or an errors dictionary. Because every error from your API looks the same, a React client can write one error handler, and tools such as validation-aware form libraries know where to find field errors. The framework already returns this shape for validation failures and can produce it for every status code when you call AddProblemDetails.

Choosing the right status code is part of the contract. Client mistakes are in the 400 range: 400 for malformed or invalid requests, 401 when the caller is not authenticated, 403 when authenticated but not permitted, 404 when the resource does not exist, 409 for conflicts such as a duplicate or a stale version, and 422 in some designs for semantic validation failures. Server faults are in the 500 range: 500 for an unexpected error, 503 when a dependency is down or the service is overloaded. A domain exception like a not-found or a conflict can be mapped to the appropriate 4xx code in the handler, while anything unrecognized becomes a generic 500 with no details.

What the response omits matters as much as what it contains. In production, an unexpected exception returns a fixed message, such as an unexpected error occurred, plus a trace identifier. The full exception, stack trace, and inner errors go to the log, tagged with the same identifier, so a developer can find them and the user cannot use them. In development you may enable the developer exception page for convenience, but it must never be reachable in production. A related security habit is consistency: an API that answers 404 for missing records but 403 for records that exist and belong to someone else lets an attacker discover which identifiers are valid, so sensitive resources often return 404 in both cases.

StatusMeaningTypical cause
400Bad requestMalformed JSON, failed validation
401UnauthenticatedMissing or invalid credential
403ForbiddenAuthenticated but not allowed
404Not foundNo such resource, or hidden from this caller
409ConflictDuplicate, or version mismatch on update
500Internal server errorUnhandled exception, details only in the log

Worked Example: A Global Handler That Maps Domain Errors and Hides the Rest

The handler below maps a few domain exceptions to specific statuses and turns everything else into a generic 500. It attaches the trace identifier so the client can quote it to support.

C#
public abstract class DomainException(string message) : Exception(message);
public sealed class NotFoundException(string message) : DomainException(message);
public sealed class ConflictException(string message) : DomainException(message);

public sealed class GlobalExceptionHandler(
    ILogger<GlobalExceptionHandler> logger,
    IProblemDetailsService problems) : IExceptionHandler
{
    public async ValueTask<bool> TryHandleAsync(HttpContext ctx, Exception ex, CancellationToken ct)
    {
        var (status, title) = ex switch
        {
            NotFoundException => (StatusCodes.Status404NotFound, "Resource not found"),
            ConflictException => (StatusCodes.Status409Conflict, "Conflict"),
            OperationCanceledException => (499, "Client closed request"),
            _ => (StatusCodes.Status500InternalServerError, "An unexpected error occurred")
        };

        // Full detail goes to the log, tagged with the trace id. Log level reflects severity.
        if (status >= 500) logger.LogError(ex, "Unhandled exception. TraceId {TraceId}", ctx.TraceIdentifier);
        else logger.LogInformation("Handled {ExceptionType}: {Message}", ex.GetType().Name, ex.Message);

        ctx.Response.StatusCode = status;
        return await problems.TryWriteAsync(new ProblemDetailsContext
        {
            HttpContext = ctx,
            ProblemDetails =
            {
                Status = status,
                Title = title,
                // Only domain exceptions carry a message safe to show; 500 gets none.
                Detail = ex is DomainException ? ex.Message : null,
                Extensions = { ["traceId"] = ctx.TraceIdentifier }
            }
        });
    }
}

// Program.cs
builder.Services.AddProblemDetails();
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
var app = builder.Build();
app.UseExceptionHandler();
app.UseStatusCodePages();       // also gives 404 and 405 with no body a ProblemDetails body

A React client can now write one function that reads status, title, detail, and traceId from any failure. In Day 55 you will map the errors dictionary from validation problems onto form fields, and in Phase 8 the trace identifier becomes a real distributed trace ID.

An endpoint throws a domain exception. The global handler logs the full detail with the trace id and returns a safe ProblemDetails response carrying only the trace id.
An endpoint throws a domain exception. The global handler logs the full detail with the trace id and returns a safe ProblemDetails response carrying only the trace id.

Real-World Examples

  • RFC 7807, published in March 2016, and its 2023 successor RFC 9457 standardize the application/problem+json media type so that HTTP APIs report errors in a machine-readable format. ASP.NET Core adopted it as the default error shape for validation failures, and many public APIs use it, which lets generic client libraries handle errors without custom parsing for each provider.
  • In September 2010, researchers Juliano Rizzo and Thai Duong demonstrated a padding oracle attack against ASP.NET that decrypted protected data by observing whether the server's error responses differed for different kinds of invalid input. Microsoft's fix in security bulletin MS10-070 included making errors uniform, and the episode is the textbook case for why distinguishable error details are a real vulnerability and not only an aesthetic concern.
Key TakeawaysRoute every unhandled failure through one exception handler that logs details privately and returns a standard ProblemDetails body with a trace identifier. Map domain errors to precise 4xx codes, return a generic message for unexpected 500s, and keep error responses uniform so they never help an attacker probe your system.

Review Questions & Answers

Per-endpoint handling produces inconsistent response shapes, gets forgotten on new endpoints, and duplicates logic. A global handler guarantees that every unhandled exception, including ones from middleware, is logged once and converted to the same safe response. Endpoints can then throw domain exceptions and focus on the happy path.

The client should see a 500 status with a generic title and a trace identifier, but no message, stack trace, or type names. The full exception belongs in the server log, tagged with the same identifier, so a developer can look it up from the identifier the user reports. This keeps internals private while keeping the failure diagnosable.

A 401 means the caller has not proven who they are, while 403 means they are known but not permitted. Returning 403 for a record that exists but belongs to someone else confirms the record exists, letting an attacker enumerate valid identifiers. Returning 404 in both cases gives away nothing, at the cost of slightly less precise feedback for legitimate users.

The client can implement one error-handling path that always reads the same fields, instead of parsing a different structure per endpoint. Form libraries can rely on the errors dictionary for field messages, and support flows can show the trace identifier. Consistency reduces client code and prevents bugs where an unusual response shape crashes the interface.