LESSON 6 OF 18

6. Centralized Error Handling and ProblemDetails

Learn how to implement centralized exception handling, IExceptionHandler, ProblemDetails, and consistent error contracts in ASP.NET Core Web APIs.

45 dk 99

Introduction

An API is not judged only by how it behaves when requests succeed. Client mistakes, missing resources, business rule violations, database conflicts, and unexpected system failures must also be handled predictably. Otherwise, every controller implements its own error checks, similar code is repeated, and clients receive different error formats from different endpoints.

In this lesson, we will build a centralized error-handling approach for an ASP.NET Core Web API. We will classify error types, produce responses that follow the ProblemDetails standard, and use the current IExceptionHandler approach available in ASP.NET Core on .NET 10. We will also discuss when a traditional middleware-based solution may be appropriate.

Goals of centralized error handling

A professional API error strategy should achieve the following:

  • Return a consistent HTTP status code for each error category.
  • Produce a standard JSON body that clients can process.
  • Prevent stack traces, internal implementation details, and sensitive data from leaking.
  • Keep sufficient logging and diagnostic information on the server.
  • Reduce repetitive try-catch blocks in controllers.
  • Make each failure traceable through a correlation or trace identifier.

For example, the same “product was not found” condition should not produce 404 from one endpoint and 400 or a successful 200 response containing an error object from another. An error contract is as important as any other API contract.

What is ProblemDetails?

ProblemDetails is a standardized model for representing HTTP API errors in a machine-readable format. A typical response may look like this:

{  "type": "https://api.example.com/problems/product-not-found",  "title": "Product not found",  "status": 404,  "detail": "The specified product does not exist.",  "instance": "/api/v1/products/42",  "traceId": "00-abc123..." }

The type identifies the category of the problem, title provides a short general description, status contains the HTTP status code, detail explains the specific request, and instance identifies the request or resource path. In production, never put a SQL exception message or stack trace in detail.

Validation errors can use ValidationProblemDetails, which includes field-level information in an errors dictionary:

{  "title": "One or more validation errors occurred.",  "status": 400,  "errors": {    "name": ["The Name field is required."],    "price": ["Price must be greater than zero."]  } }

Application-specific exception types

To make the mapping between exceptions and status codes explicit, define exceptions that represent application-level meanings rather than framework implementation details.

public abstract class ApiException : Exception {    protected ApiException(string message) : base(message) { } } public sealed class ResourceNotFoundException : ApiException {    public ResourceNotFoundException(string resource, object key)        : base($"{resource} with key '{key}' was not found.") { } } public sealed class ConflictException : ApiException {    public ConflictException(string message) : base(message) { } } public sealed class BusinessRuleException : ApiException {    public BusinessRuleException(string message) : base(message) { } }

These classes represent business meaning exposed by the application. Instead of allowing a provider-specific EF Core exception to leak into a controller, translate a uniqueness violation into a ConflictException where appropriate.

Configuring AddProblemDetails

First, register the ProblemDetails services. Then enable the exception handler middleware and status code pages for error responses that do not already have a body.

var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); builder.Services.AddProblemDetails(options => {    options.CustomizeProblemDetails = context =>    {        var httpContext = context.HttpContext;        context.ProblemDetails.Extensions["traceId"] =            httpContext.TraceIdentifier;    }; }); builder.Services.AddExceptionHandler<ApiExceptionHandler>(); var app = builder.Build(); if (!app.Environment.IsDevelopment()) {    app.UseExceptionHandler(); } app.UseStatusCodePages(); app.MapControllers(); app.Run();

AddProblemDetails registers ASP.NET Core’s IProblemDetailsService implementation. UseExceptionHandler catches unhandled exceptions, while UseStatusCodePages can generate ProblemDetails for eligible 4xx and 5xx responses that have no body.

The developer exception page can be useful during development, but it must not expose stack traces to production clients. Environment-specific configuration is therefore essential.

Implementing IExceptionHandler

IExceptionHandler moves exception processing into a separate, testable class. When the handler handles an exception, it should write the complete response and return true.

using Microsoft.AspNetCore.Diagnostics; using Microsoft.AspNetCore.Mvc; public sealed class ApiExceptionHandler : IExceptionHandler {    private readonly ILogger<ApiExceptionHandler> _logger;    public ApiExceptionHandler(ILogger<ApiExceptionHandler> logger)    {        _logger = logger;    }    public async ValueTask<bool> TryHandleAsync(        HttpContext httpContext,        Exception exception,        CancellationToken cancellationToken)    {        var (status, title, detail) = exception switch        {            ResourceNotFoundException ex =>                (StatusCodes.Status404NotFound, "Resource not found", ex.Message),            ConflictException ex =>                (StatusCodes.Status409Conflict, "Conflict", ex.Message),            BusinessRuleException ex =>                (StatusCodes.Status422UnprocessableEntity, "Business rule violation", ex.Message),            _ =>                (StatusCodes.Status500InternalServerError,                 "An unexpected error occurred",                 "The server could not complete the request.")        };        if (status >= 500)            _logger.LogError(exception, "Unhandled API exception. TraceId: {TraceId}",                httpContext.TraceIdentifier);        else            _logger.LogWarning(exception, "Handled API exception. TraceId: {TraceId}",                httpContext.TraceIdentifier);        httpContext.Response.StatusCode = status;        var problem = new ProblemDetails        {            Status = status,            Title = title,            Detail = detail,            Instance = httpContext.Request.Path        };        problem.Extensions["traceId"] = httpContext.TraceIdentifier;        await httpContext.Response.WriteAsJsonAsync(problem, cancellationToken);        return true;    } }

Unexpected exceptions receive a stable and safe client message. The real exception is logged, but its raw message is not forwarded to the client. This separation is critical for security and operational diagnostics.

In .NET 10, diagnostics for exceptions handled by an IExceptionHandler may be suppressed by default when the handler returns true. Define your logging policy deliberately, and avoid logging the same handled exception twice at both middleware and handler levels.

Simplifying controller code

Before centralized handling, a controller action may contain code like this:

[HttpGet("{id:int}")] public async Task<ActionResult<ProductResponse>> GetById(int id) {    try    {        var product = await service.GetByIdAsync(id);        if (product is null)            return NotFound(new { message = "Product not found" });        return Ok(product);    }    catch (Exception)    {        return StatusCode(500, new { message = "Unexpected error" });    } }

Every action repeats the same responsibilities. Instead, the service can throw ResourceNotFoundException when a product is missing, while the controller represents only the successful flow:

[HttpGet("{id:int}")] public async Task<ActionResult<ProductResponse>> GetById(int id) {    var product = await service.GetByIdAsync(id);    return Ok(product); }

This does not mean exceptions should be used for every possible outcome. Frequent, expected validation results can be modeled as normal results. Exceptions are most appropriate for failures that interrupt the normal flow, such as an invalid business operation or an unexpected infrastructure problem.

Distinguishing validation, not-found, and conflict

SituationSuggested codeExample
Invalid JSON or field validation400Missing or incorrectly formatted input
Missing authentication401No valid access token
Insufficient permission403User cannot access the resource
Resource does not exist404Product id was not found
Conflict with current state409Email address is already registered
Business rule violation422Order cannot be placed because stock is insufficient
Unexpected server failure500Unanticipated application or infrastructure error

There is not always one universally correct choice, but consistency across the API is essential. Do not confuse validation with a business rule violation. “Price must be numeric” is a validation problem. “Discounted price cannot be greater than the regular price” is a business rule.

Trace identifiers and logging

If the client sees only “an internal server error occurred,” support teams have little information to investigate. Include a traceId in the response and use the same identifier in log entries. HttpContext.TraceIdentifier is a useful starting point. In distributed systems, W3C trace context and OpenTelemetry can provide more complete request tracing.

Never log passwords, access tokens, payment card data, or sensitive personal information. Rather than logging the entire request body, record controlled fields such as the endpoint, status code, trace identifier, user or tenant identifier, and relevant business keys.

Common mistakes

  • Using try-catch everywhere: Repetition increases and the real error flow becomes harder to understand.
  • Returning raw exception messages: Database details, file paths, and internal services may be exposed.
  • Returning 500 for every failure: Client errors become indistinguishable from server failures.
  • Returning every error as 200: HTTP clients make incorrect retry, caching, and monitoring decisions.
  • Returning true without writing a response: The handler may produce an incomplete or meaningless response.
  • Using development settings in production: Stack traces and sensitive details can leak.
  • Modeling validation as exceptions: Normal, user-correctable input errors should remain validation results.

Practice exercise

  1. Add ApiException, ResourceNotFoundException, and ConflictException to the existing product API.
  2. Configure AddProblemDetails and UseExceptionHandler in Program.cs.
  3. Implement IExceptionHandler for 404, 409, 422, and 500 responses.
  4. Request a missing product and inspect the application/problem+json response.
  5. Try creating a second user with the same email address and return a 409 response.
  6. Trigger an unexpected exception and verify that the client receives a safe message while the server log contains the detailed exception and trace identifier.
  7. Confirm that model validation still returns field-level errors rather than being converted into a generic exception response.

Conclusion

Centralized error handling makes controller code smaller and API behavior more predictable. ProblemDetails gives clients a common error contract, while IExceptionHandler keeps exception translation in one place. When status codes, safe messages, logging, and trace information are designed together, the API behaves professionally not only during successful requests but also when failures occur.

Sources