Consistent Error Responses in ASP.NET Core APIs: ProblemDetails and Centralized Exception Handling

Consistent Error Responses in ASP.NET Core APIs: ProblemDetails and Centralized Exception Handling

An API is not judged only by the data it returns when everything works. Invalid input, missing resources, authorization failures, dependency outages, and unexpected exceptions are all part of the API contract. If every endpoint returns a different error shape, client applications need endpoint-specific parsing logic and support teams have difficulty connecting a reported failure to server-side logs.

ASP.NET Core provides ProblemDetails and centralized exception handling features that help establish a predictable error contract. The result can include the HTTP status code, a general title, a safe description, and an identifier that makes the request easier to trace.

What ProblemDetails provides

ProblemDetails is a model for representing HTTP API errors in a machine-readable format. Common members include:

  • type: A URI identifying the problem type.
  • title: A short, general description.
  • status: The HTTP status code generated for the response.
  • detail: A request-specific explanation.
  • instance: A URI or identifier for the occurrence.

Not every response needs every property. More importantly, production responses should not expose stack traces, database messages, internal type names, connection strings, or other implementation details. Those details are useful in logs, but can disclose sensitive information when sent to clients.

Configure the common pipeline

A basic setup registers the problem details service and enables middleware for exceptions and status-code responses:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddProblemDetails();

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler();
}

app.UseStatusCodePages();
app.MapControllers();

app.Run();

AddProblemDetails registers the default service used to create problem responses. UseExceptionHandler catches unhandled exceptions and prevents development-only exception details from being returned in production. UseStatusCodePages can produce a problem response for client and server error status codes that do not already have a response body.

Development exception pages are valuable during local development, but they should never be enabled for public production traffic. A production client normally needs a stable message and a trace identifier, not a stack trace.

Handle known exceptions centrally

Putting try-catch blocks in every controller duplicates infrastructure code and often creates inconsistent response formats. A centralized exception handler can translate known application exceptions into intentional HTTP responses.

Modern ASP.NET Core applications can implement IExceptionHandler. The handler returns true when it has produced a response and false when another handler or the default middleware should continue:

using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;

public sealed class ApiExceptionHandler(
    ILogger<ApiExceptionHandler> logger) : IExceptionHandler
{
    public async ValueTask<bool> TryHandleAsync(
        HttpContext httpContext,
        Exception exception,
        CancellationToken cancellationToken)
    {
        if (exception is not DomainException domainException)
        {
            return false;
        }

        logger.LogWarning(exception, "A domain error occurred");

        var problem = new ProblemDetails
        {
            Status = StatusCodes.Status422UnprocessableEntity,
            Title = "The request could not be processed",
            Detail = domainException.Message,
            Instance = httpContext.Request.Path
        };

        problem.Extensions["traceId"] = httpContext.TraceIdentifier;

        httpContext.Response.StatusCode = problem.Status.Value;
        await httpContext.Response.WriteAsJsonAsync(
            problem,
            cancellationToken);

        return true;
    }
}

Here, DomainException represents an exception type owned by the application. The handler deliberately handles only an expected business-rule failure. An unrelated programming error or infrastructure exception returns false, allowing the general exception middleware to apply its safe fallback behavior.

Register the handler and enable the middleware:

builder.Services.AddExceptionHandler<ApiExceptionHandler>();
builder.Services.AddProblemDetails();

var app = builder.Build();
app.UseExceptionHandler();

Exception handlers should remain focused. They can log and translate an exception, but business decisions should normally remain in the application or domain layer rather than in the HTTP adapter.

Choose status codes deliberately

Status codes are part of the contract because clients often use them to decide whether to display validation feedback, request authentication, or retry:

StatusTypical meaning
400The request syntax or parameters are invalid.
401Authentication is missing or unsuccessful.
403The caller is authenticated but not allowed to perform the operation.
404The requested resource does not exist.
409The request conflicts with the current state of a resource.
422The request is understandable but violates an application rule.
500An unexpected server-side failure occurred.
503A service or dependency is temporarily unavailable.

This is a design guide, not a requirement to use every code. Consistency matters more than having a large catalogue. For example, if a duplicate command always maps to 409, every client can handle that case predictably.

Represent validation failures clearly

Controller-based Web APIs commonly return ValidationProblemDetails when model validation fails. Its field-oriented error dictionary allows a client to display messages beside the relevant input:

{
  "type": "https://example.com/problems/validation",
  "title": "Validation failed",
  "status": 400,
  "errors": {
    "email": ["A valid email address is required."],
    "quantity": ["Quantity must be greater than zero."]
  },
  "traceId": "00-abc123"
}

Keeping the keys aligned with public request DTO property names makes client integration easier. Avoid exposing database column names or internal object paths. The public error contract should reflect the API model, not the internal persistence model.

Customize shared metadata

Applications often need common metadata such as a trace identifier or service name. Problem details customization can add these fields centrally:

builder.Services.AddProblemDetails(options =>
{
    options.CustomizeProblemDetails = context =>
    {
        context.ProblemDetails.Extensions["traceId"] =
            context.HttpContext.TraceIdentifier;
        context.ProblemDetails.Extensions["service"] = "orders-api";
    };
});

A trace identifier helps support engineers connect a client-visible failure with structured logs and distributed tracing. It should be treated as a correlation aid, not as permission to reveal internal infrastructure. Never place credentials, access tokens, personal data, or raw exception messages in a shared error payload without a clear security review.

Keep the contract stable

A useful error contract is intentionally small. Clients generally need a status, a stable problem type or application error code, a safe title, optional field errors, and a trace identifier. They do not need a separate response schema for every exception class.

  1. Use one JSON error format across controllers and minimal API endpoints where practical.
  2. Choose status codes according to semantics rather than convenience.
  3. Map expected domain exceptions in a central handler.
  4. Return a generic response for unknown exceptions while logging the full diagnostic context on the server.
  5. Use stable problem types or application codes when clients must branch on a specific condition.
  6. Keep validation keys tied to public DTO fields.
  7. Test both the status code and the response body as part of the API contract.

Testing the error behavior

Integration tests should verify representative failures: malformed input, validation errors, missing resources, authorization failures, conflicts, and an unexpected exception. The tests should confirm that the response has the expected status, content type, stable fields, and no sensitive details.

It is also useful to test that an endpoint which already writes a response is not overwritten by status-code middleware. Error infrastructure should complete missing responses rather than replace intentional endpoint payloads.

Conclusion

Consistent error handling improves both client development and operational troubleshooting. ProblemDetails supplies a common transport shape, while IExceptionHandler provides a focused place to translate known application failures. Together with deliberate status-code choices, field-level validation errors, safe production messages, and trace identifiers, they create an API contract that is easier to consume and maintain.

The goal is not to expose every detail of a failure. The goal is to communicate the right amount of information to the client and preserve the complete diagnostic context for the server-side team.

Sources

//

0 Comments

Write Comment

E-Mail address will not be published