Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Lesson2 / 13

    API Error Handling in ASP.NET Core: ProblemDetails (RFC 9457) and IExceptionHandler

    What this lesson teaches

    Global error handling in ASP.NET Core turns failures into consistent ProblemDetails responses. Learn which errors need results, exceptions, and safe logging.

    The usual setup is AddProblemDetails, UseExceptionHandler with an IExceptionHandler, and UseStatusCodePages. Together, they cover exceptions and error responses that have no body. Keep private diagnostic information in logs, not in responses.

    By the end, you can design an error format, map a known business exception, and explain why an unexpected failure becomes a safe 500 response.

    What is ProblemDetails?

    ProblemDetails is the standard JSON format for describing an HTTP API error. RFC 9457, published in July 2023, replaced RFC 7807. ASP.NET Core provides built-in ProblemDetails support.

    The example below uses application/problem+json as its response media type. A media type identifies the format of a response body through its Content-Type header.

    The format defines five standard members. They are not all required in every response. When type is missing, its value is about:blank: the problem means nothing beyond its HTTP status code.

    MemberWhat it means
    typeIdentifies the kind of problem, such as an order that cannot be cancelled.
    titleA short description of that kind of problem.
    statusThe HTTP status code associated with this occurrence.
    detailA safe explanation of this particular failure.
    instanceIdentifies this particular occurrence, rather than the general problem kind.

    The type member is a URI reference: an identifier written using the same syntax family as URLs. It identifies the problem, not the C# exception class.

    For your own problem types, choose absolute URIs, such as https://api.example.com/problems/order-shipped. An absolute URI includes its scheme, such as https, rather than depending on a base address. Publish documentation at these addresses and keep them stable. Changing a problem's type changes its identity and can break clients that recognize it.

    When you include status, make it match the actual HTTP response status. A JSON body containing "status": 404 does not turn an HTTP 200 response into a 404.

    ProblemDetails also allows extensions: extra members your API defines, such as a stable error code. Clients must ignore extension members they do not recognize, so you can add new ones without breaking them.

    This small example builds a response so you can inspect its JSON and media type. It runs without ASP.NET Core packages. It does not test the framework's error-handling behavior; the later server example does that.

    C#Runs
    using System.Net;
    using System.Net.Http.Headers;
    using System.Text.Json;
    
    using var response = new HttpResponseMessage(HttpStatusCode.NotFound)
    {
        Content = new StringContent("""
            {"type":"https://api.example.com/problems/not_found","title":"Order not found","status":404,"detail":"Order not found.","code":"not_found"}
            """)
    };
    response.Content.Headers.ContentType =
        new MediaTypeHeaderValue("application/problem+json");
    
    var body = await response.Content.ReadAsStringAsync();
    using var document = JsonDocument.Parse(body);
    Console.WriteLine($"Content-Type: {response.Content.Headers.ContentType}");
    Console.WriteLine(body);
    Console.WriteLine($"status matches: {document.RootElement.GetProperty("status").GetInt32() == (int)response.StatusCode}");
    Output
    Content-Type: application/problem+json
    {"type":"https://api.example.com/problems/not_found","title":"Order not found","status":404,"detail":"Order not found.","code":"not_found"}
    status matches: True

    The mistake to avoid. Do not make clients interpret detail to decide what to do. Its wording can change. Use the problem's identity or a documented error code.

    In an interview, say: “ProblemDetails is the RFC 9457 error format, normally sent as application/problem+json. It defines type, title, status, detail, and instance. The type identifies the problem kind, and extensions carry API-specific information.”

    Design a small error contract

    An error contract is the agreement between your API and its clients about error meanings and fields. Start with a short catalogue, not a different format for each endpoint.

    Problem kindTypical statusExample stable code
    Validation: submitted data is invalid400, or a documented 422 policyvalidation_failed
    Not found: the requested resource is missing404not_found
    Conflict: the operation conflicts with current state409order_shipped
    Precondition: a required condition is missing or false428 when required; 412 when falseprecondition_required, precondition_failed
    Rate limit: the client has sent too many requests429rate_limited

    Give each problem kind its own documented type. Keep a code extension stable too, especially if clients use it for decisions. If you expose both identifiers, document their relationship so they cannot drift apart.

    A trace ID is an identifier support staff can use to find the corresponding request in diagnostic records. AddProblemDetails already adds a traceId to responses written by the problem-details service. Keep it, and make sure your logs record the same ID.

    Never return stack traces, SQL, secrets, or internal host names and addresses. These details help developers, but they can expose how the application is built or configured.

    A useful public detail is “This order has already shipped.” An unsafe detail is the database exception message behind that decision. The Developer Exception Page is a built-in page that shows the exception, its stack trace and request data. It is meant for local development only and must not be enabled in production.

    The mistake to avoid. Do not copy exception.Message into every response. Unexpected messages can contain private information, and they are not a stable client contract.

    In an interview, say: “I return a stable problem type and code with a safe explanation. AddProblemDetails adds a traceId by default. I keep it and make sure logs and traces record the same ID, so support can connect a client's error to server records. Private details stay in protected logs.”

    Use results for expected failures

    An order that does not exist is an expected outcome of a lookup. Return a result describing that outcome instead of throwing an exception just to choose an HTTP status.

    In a Minimal API, you connect a URL pattern (a route, such as /orders/{id}) directly to a method that handles it, without a controller class. TypedResults.Problem returns a ProblemHttpResult. It writes a ProblemDetails body, and its type can appear in the method's return type. Results<Ok<string>, ProblemHttpResult> declares the allowed alternatives: success with text or a problem response.

    These alternatives do not document your individual problem types. Minimal APIs vs controllers covers typed results.

    Results are also cheaper than throwing exceptions for routine control flow. Exceptions require additional work to throw and handle. Use exceptions for unexpected failures, such as a programming error or an unavailable database or external service.

    Some existing business code already throws named exceptions. A domain exception represents a failure in the application's business rules. You can translate a known exception such as OrderShippedException into 409 in one place at the edge of the API, where HTTP responses are made. An IExceptionHandler, introduced below, is one place to do this. Do not infer the response from its message.

    flowchart TD
        A["Failure"] -->|"is expected"| B["Return a result"]
        A -->|"is thrown"| C["Exception handler"]
        C -->|"recognizes rule"| D["Documented problem"]
        C -->|"does not recognize"| E["Safe 500 problem"]

    Expected outcomes return directly; thrown failures pass through the exception handler.

    The mistake to avoid. Do not turn every business decision into an exception just because a global handler exists. Keep normal alternatives visible where the decision is made.

    In an interview, say: “I use typed results for expected outcomes because they are explicit, documentable, and avoid exception overhead. I reserve exceptions for unexpected failures. If existing business code throws a known domain exception, I map it deliberately.”

    Wire global error handling in ASP.NET Core

    Middleware is a request-processing component that can run code before and after the next component. Exception-handling middleware can catch exceptions from components that run after it.

    IExceptionHandler gives ASP.NET Core a method to ask whether your class handled an exception. You can register several handlers. ASP.NET Core calls them in registration order and stops at the first one that returns true. If all return false, the exception middleware uses its default handling.

    For global errors, prefer exception middleware with IExceptionHandler over MVC exception filters. MVC exception filters are error-handling components for controller processing, including controller methods and their action filters. They do not cover failures elsewhere in the request pipeline. Exception middleware can catch failures in any component that runs after it, including components outside controllers.

    Registration and middleware have different jobs:

    • AddProblemDetails registers the default IProblemDetailsService implementation.
    • UseExceptionHandler handles otherwise unhandled exceptions and consults registered exception handlers.
    • UseStatusCodePages writes a body for error responses (status 400 to 599) that have no body yet. It does not catch exceptions.

    The example below uses CustomizeProblemDetails to supply its public type, instance, and code.

    The exception-handling and ProblemDetails mechanics lesson explains the request-processing details. Here, focus on the public contract.

    See the contract in one program

    This example uses TestServer, an in-memory server for testing ASP.NET Core without opening a network port. Its HttpClient sends requests directly to that server.

    It needs ASP.NET Core and Microsoft.AspNetCore.TestHost, so it does not run in the site's package-free console runner.

    Before reading the code, predict the statuses for a missing order, a shipped order, and an unexpected exception.

    The handler returns ValueTask<bool>, an asynchronous result whose Boolean says whether it handled the exception. IProblemDetailsService.TryWriteAsync reports whether it could write the response.

    C#
    using System.Text.Json;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Diagnostics;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Http.HttpResults;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.TestHost;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Logging;
    
    var builder = WebApplication.CreateBuilder(new WebApplicationOptions
    {
        EnvironmentName = "Production"
    });
    builder.WebHost.UseTestServer();
    // Keep this demonstration's console output short. Retain logs in production.
    builder.Logging.ClearProviders();
    builder.Services.AddExceptionHandler<OrderExceptionHandler>();
    builder.Services.AddProblemDetails(options =>
    {
        options.CustomizeProblemDetails = context =>
        {
            var problem = context.ProblemDetails;
            var code = problem.Status switch
            {
                404 => "not_found",
                409 => "order_shipped",
                _ => "internal_error"
            };
            problem.Type = $"https://api.example.com/problems/{code}";
            problem.Instance = context.HttpContext.Request.Path.Value;
            problem.Extensions["code"] = code;
        };
    });
    
    await using var app = builder.Build();
    app.UseExceptionHandler();
    app.UseStatusCodePages();
    app.MapGet("/orders/{id:int}", GetOrder);
    app.MapPost("/orders/1/cancel", CancelOrder);
    app.MapGet("/fail", Fail);
    await app.StartAsync();
    
    using var client = app.GetTestClient();
    client.DefaultRequestHeaders.Accept.ParseAdd("application/problem+json");
    foreach (var (method, path) in new[]
    {
        (HttpMethod.Get, "/orders/99"),
        (HttpMethod.Post, "/orders/1/cancel"),
        (HttpMethod.Get, "/fail")
    })
    {
        using var request = new HttpRequestMessage(method, path);
        using var response = await client.SendAsync(request);
        var body = await response.Content.ReadAsStringAsync();
        using var document = JsonDocument.Parse(body);
        var problem = document.RootElement;
        Console.WriteLine($"{(int)response.StatusCode}: {problem.GetProperty("code").GetString()}");
        Console.WriteLine($"type: {problem.GetProperty("type").GetString()}");
        Console.WriteLine($"status matches: {problem.GetProperty("status").GetInt32() == (int)response.StatusCode}");
        Console.WriteLine($"traceId present: {problem.TryGetProperty("traceId", out _)}");
        Console.WriteLine($"private message exposed: {body.Contains("Private database failure")}");
    }
    
    static Results<Ok<string>, ProblemHttpResult> GetOrder(int id)
        => id == 1
            ? TypedResults.Ok("Order 1")
            : TypedResults.Problem(statusCode: 404, detail: "Order not found.");
    
    static IResult CancelOrder() => throw new OrderShippedException();
    static IResult Fail() => throw new InvalidOperationException("Private database failure");
    
    public sealed class OrderShippedException : Exception { }
    
    public sealed class OrderExceptionHandler(IProblemDetailsService problems)
        : IExceptionHandler
    {
        public async ValueTask<bool> TryHandleAsync(
            HttpContext context, Exception exception, CancellationToken cancellationToken)
        {
            if (exception is not OrderShippedException)
                return false;
    
            context.Response.StatusCode = StatusCodes.Status409Conflict;
            return await problems.TryWriteAsync(new ProblemDetailsContext
            {
                HttpContext = context,
                ProblemDetails = new ProblemDetails
                {
                    Status = StatusCodes.Status409Conflict,
                    Title = "Order cannot be cancelled",
                    Detail = "This order has already shipped."
                }
            });
        }
    }
    Output
    404: not_found
    type: https://api.example.com/problems/not_found
    status matches: True
    traceId present: True
    private message exposed: False
    409: order_shipped
    type: https://api.example.com/problems/order_shipped
    status matches: True
    traceId present: True
    private message exposed: False
    500: internal_error
    type: https://api.example.com/problems/internal_error
    status matches: True
    traceId present: True
    private message exposed: False

    Needs ASP.NET Core (a web project) and the package Microsoft.AspNetCore.Mvc.Testing 10.0.12. Built and run on the in-memory TestServer: the output above is what it printed.

    First, GetOrder returns a 404 problem directly. The customization supplies our own type, instance, and code.

    Second, cancelling the shipped order throws OrderShippedException. The registered handler recognizes it and sets both the HTTP status and problem status to 409.

    Third, /fail throws an exception the handler does not recognize. Returning false leaves it for the exception middleware, which produces a safe 500 problem. The private exception message is not used as public detail.

    The checks print stable contract fields and whether a trace ID exists, not the changing ID itself. The example's status-to-code mapping covers only these three cases. A real API needs its full catalogue, including distinct problems that share a status.

    The api.example.com addresses are placeholders. Replace them with your own stable, documented problem identifiers.

    The mistake to avoid. Do not assume status code pages rewrite every error response. They fill eligible empty responses; they do not replace a body your endpoint already wrote.

    In an interview, say: “TryHandleAsync returns true when the exception is handled. Handlers run in registration order until one returns true. If all return false, the middleware uses its default handling. I prefer middleware with IExceptionHandler for global errors because it catches downstream failures beyond controllers; MVC exception filters are limited to controller processing.”

    Check yourself

    A lookup finds no matching order. What should a newly designed endpoint normally do?

    A Return a 404 problem result from the endpoint
    B Throw an exception so the global handler can choose 404
    C Return HTTP 200 with status 404 in the JSON body
    D Return 404 with the database exception message as detail
    Show answer

    Correct answer: A

    A missing order is an expected lookup outcome. Return it explicitly, and keep the HTTP status consistent with the problem body.

    Which response detail is appropriate for an unexpected production failure?

    A The failing SQL query, so support can reproduce it
    B The database host name, so operators can find the server
    C The exception stack trace, to speed up debugging
    D A short safe message and a traceId found in the logs
    Show answer

    Correct answer: D

    Clients need a safe response and a way to contact support. Internal failure details belong in protected logs.

    Going deeper

    Response format negotiation matters. The Accept request header tells the server which response formats the client accepts. The default writer writes the problem when the Accept header allows application/json or application/problem+json, including through */* or application/*. It also writes when there is no Accept header. It does not write for text/html only. Customization through the problem service is therefore not a guarantee for every response-writing path. We sent this lesson's program Accept: text/html on .NET 10.0.12. The 404 came back as problem JSON without our type, code, instance and traceId, because the customization did not run. The 409 and the 500 came back with empty bodies. Decide and test your fallback policy. See Microsoft's API error-handling guidance.

    Do not build a contract around framework defaults. In the checked .NET 10.0.12 response, the default 500 title was “An error occurred while processing your request.” In .NET 11.0.0, it was “Internal Server Error”. Clients should not branch on either title. The checked defaults also supplied no type link for 428 or 429, and the 422 link referred to RFC 4918 rather than RFC 9110. Set your own types instead of depending on those links.

    Validation extensions can differ. RFC 9457's validation example uses an errors array with JSON Pointers. A JSON Pointer identifies a location within a JSON document. ASP.NET Core's validation problem responses instead use an errors dictionary. Both are extensions, not a universal RFC-defined validation structure. Document which shape your API returns.

    Preserve client-error statuses when handling binding failures. Binding turns incoming request data into handler arguments. When ThrowOnBadRequest is enabled, binding failures throw BadHttpRequestException. ASP.NET Core 11 preserves its status by default through UseExceptionHandler. In ASP.NET Core 10 and earlier, an unhandled exception defaults to 500 unless handling explicitly preserves the exception's status in both the response and body. Custom handlers must still preserve it deliberately.

    There are limits to global handling. A response has started when its status line and headers have already been sent to the client; they cannot be taken back. An exception handler then cannot reliably replace it with a fresh problem response. In .NET 10, when your handler returns true, the exception middleware no longer writes its own log entry or metrics for that exception. You can change this with ExceptionHandlerOptions.SuppressDiagnosticsCallback. Arrange logging deliberately rather than assuming every mapped exception will automatically appear in logs.

    Sources

    Sign in to mark lessons done and keep your place in the course.Sign in

    Checked before publishing: C# examples run on .NET 10, links opened, reviewed while it was written and read in full. How lessons are checked

    Updated 1 Dec 2026 ·