When an application has multiple APIs, error handling often becomes inconsistent. One controller returns a simple string when something goes wrong, another returns an object containing an error message, and a third exposes exception details directly. Even when all these APIs belong to the same organization, their clients must understand different response formats.
This creates unnecessary work for frontend developers, mobile application developers, and other services that consume the APIs. They need separate error-handling logic for different endpoints, and troubleshooting becomes more difficult because there is no common structure for identifying failures.
ASP.NET Core provides built-in support for ProblemDetails, a standard format for describing HTTP API errors. It allows applications to return structured error information using a consistent response model. When multiple APIs share the same error-handling approach, clients can process errors in a predictable way regardless of which service generated them.
This article explains how to use ProblemDetails in ASP.NET Core, centralize exception handling, customize error responses, handle validation failures, and share the same approach across multiple APIs.
Why APIs Need a Common Error Response
Consider an application with three services:
- Customer API manages customer information.
- Order API processes customer orders.
- Payment API handles payment operations.
Each API may return a different response when an operation fails.
The Customer API might return:
{
"message": "Customer not found"
}
The Order API might return:
{
"success": false,
"errorCode": 404,
"description": "The requested order does not exist"
}
The Payment API might return:
Payment processing failed.
These responses communicate similar information, but their structures are different. A client application must implement separate parsing logic for each API. It may also need special handling to identify error codes, display messages, and decide whether an operation can be retried.
A common error format removes much of this complexity.
ProblemDetails follows RFC 9457, which defines a standard way to carry machine-readable information about HTTP API errors. It provides a predictable structure that clients can understand without requiring every API to invent its own error format.
A typical ProblemDetails response looks like this:
{
"type": "https://api.example.com/problems/customer-not-found",
"title": "Customer not found",
"status": 404,
"detail": "The requested customer could not be found.",
"instance": "/api/customers/100"
}
Each property has a specific purpose:
| Property | Purpose |
|---|
| type | Identifies the problem category. |
| title | Provides a short description of the problem type. |
| status | Contains the HTTP status code. |
| detail | Explains the specific problem occurrence. |
| instance | Identifies the request or resource associated with the problem. |
The type property is particularly useful when clients need to distinguish between different business errors that share the same HTTP status code. For example, two different operations might return HTTP 409, but one could represent a duplicate order while another represents an account that cannot be modified.
ProblemDetails also supports extension properties. An application can include additional information, such as an error code or trace identifier, without changing the standard structure.
Enable ProblemDetails in ASP.NET Core
ASP.NET Core provides the AddProblemDetails extension method to register the default ProblemDetails service.
Start by configuring the services in Program.cs:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddProblemDetails();
var app = builder.Build();
app.UseExceptionHandler();
app.UseStatusCodePages();
app.MapControllers();
app.Run();
This configuration enables ProblemDetails support for appropriate error responses.
The AddProblemDetails method registers the default IProblemDetailsService implementation. ASP.NET Core middleware can use this service to generate structured error responses.
Two middleware components are important here.
UseExceptionHandler handles unhandled exceptions and can produce a ProblemDetails response when the application has registered the service. UseStatusCodePages handles error status codes that do not already have response content.
For example, an endpoint that returns a 404 status without a response body can receive a ProblemDetails response through status code pages.
The middleware should be placed early enough in the request pipeline to observe failures from the components it needs to handle. Authentication, authorization, routing, and endpoint execution should be configured with the intended error-handling behavior in mind.
ASP.NET Core also considers the client's Accept header when writing a response. The default ProblemDetails writer supports JSON-related media types, including application/json and application/problem+json. If the client requests an unsupported format, the default writer may not produce the expected response.
Customize ProblemDetails for All APIs
The default response is useful, but applications often need additional information for troubleshooting. For example, developers may want every error response to include a trace identifier that can be searched in application logs.
ASP.NET Core supports global customization through ProblemDetailsOptions.CustomizeProblemDetails.
Update the registration:
builder.Services.AddProblemDetails(options =>
{
options.CustomizeProblemDetails = context =>
{
context.ProblemDetails.Extensions["traceId"] =
context.HttpContext.TraceIdentifier;
context.ProblemDetails.Extensions["service"] =
"CustomerApi";
};
});
Now automatically generated ProblemDetails responses can include the additional properties:
{
"type": "about:blank",
"title": "Not Found",
"status": 404,
"traceId": "0HNA123456789:00000001",
"service": "CustomerApi"
}
The trace identifier helps connect an HTTP response to the corresponding server-side logs. When a client reports a failure, support teams can use this identifier to locate the request without asking the client to provide internal exception information.
The service name can also help when several APIs follow the same error format. In a shared library, it is better to obtain this value from configuration rather than hardcoding it in every application.
For example:
builder.Services.AddProblemDetails(options =>
{
options.CustomizeProblemDetails = context =>
{
var configuration =
context.HttpContext.RequestServices
.GetRequiredService<IConfiguration>();
context.ProblemDetails.Extensions["traceId"] =
context.HttpContext.TraceIdentifier;
context.ProblemDetails.Extensions["service"] =
configuration["Application:Name"] ?? "UnknownApi";
};
});
This approach allows Customer API, Order API, and Payment API to use the same customization logic while providing their own service names.
Do not add sensitive information to these extensions. Database connection details, internal exception messages, access tokens, and infrastructure information should remain on the server.
Handle Exceptions Centrally With IExceptionHandler
Global ProblemDetails customization handles generated responses, but business applications also need to translate known exceptions into appropriate HTTP status codes.
For example:
- A customer lookup failure should return 404.
- An attempt to create an existing resource might return 409.
- An unexpected database or application failure should return 500.
Without centralized exception handling, developers may add similar try-catch blocks to multiple controllers. This creates duplicated code and makes it difficult to maintain consistent behavior.
ASP.NET Core provides the IExceptionHandler interface for centralized exception handling.
First, define application exceptions:
public sealed class CustomerNotFoundException : Exception
{
public CustomerNotFoundException(int customerId)
: base($"Customer {customerId} was not found.")
{
}
}
public sealed class DuplicateCustomerException : Exception
{
public DuplicateCustomerException()
: base("A customer with the same information already exists.")
{
}
}
These exceptions represent known business conditions. The exception messages are useful for server-side diagnostics, but they should not automatically be returned to clients.
Next, implement the exception handler:
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
public sealed class ApiExceptionHandler : IExceptionHandler
{
private readonly ILogger<ApiExceptionHandler> _logger;
private readonly IProblemDetailsService _problemDetailsService;
public ApiExceptionHandler(
ILogger<ApiExceptionHandler> logger,
IProblemDetailsService problemDetailsService)
{
_logger = logger;
_problemDetailsService = problemDetailsService;
}
public async ValueTask<bool> TryHandleAsync(
HttpContext httpContext,
Exception exception,
CancellationToken cancellationToken)
{
var (status, title, detail, type) = exception switch
{
CustomerNotFoundException =>
(
StatusCodes.Status404NotFound,
"Customer not found",
"The requested customer could not be found.",
"https://api.example.com/problems/customer-not-found"
),
DuplicateCustomerException =>
(
StatusCodes.Status409Conflict,
"Duplicate customer",
"A customer with the supplied information already exists.",
"https://api.example.com/problems/duplicate-customer"
),
_ =>
(
StatusCodes.Status500InternalServerError,
"Internal server error",
"An unexpected error occurred.",
"https://api.example.com/problems/internal-error"
)
};
if (status == StatusCodes.Status500InternalServerError)
{
_logger.LogError(
exception,
"An unexpected error occurred while processing a request.");
}
else
{
_logger.LogInformation(
"Request failed with status code {StatusCode}: {ExceptionType}",
status,
exception.GetType().Name);
}
httpContext.Response.StatusCode = status;
var problemDetails = new ProblemDetails
{
Status = status,
Title = title,
Detail = detail,
Type = type,
Instance = httpContext.Request.Path
};
return await _problemDetailsService.TryWriteAsync(
new ProblemDetailsContext
{
HttpContext = httpContext,
ProblemDetails = problemDetails
});
}
}
The handler maps known exceptions to appropriate status codes and problem types. Unknown exceptions receive a generic 500 response.
The important detail is that the client receives a safe description rather than the original exception message. The complete exception is logged on the server, where developers can investigate it.
The TryWriteAsync method uses the registered ProblemDetails service. This means the global customization configured earlier can also apply to responses written through this handler.
Register the handler in Program.cs:
builder.Services.AddExceptionHandler<ApiExceptionHandler>();
builder.Services.AddProblemDetails();
var app = builder.Build();
app.UseExceptionHandler();
app.UseStatusCodePages();
app.MapControllers();
app.Run();
The order of service registration is not important here, but both services must be registered before the application starts.
This implementation gives controllers a cleaner responsibility. They can call application services and allow known exceptions to reach the centralized handler rather than formatting every error response themselves.
Return Consistent Validation Errors
Validation errors are among the most common API failures. A client may submit a missing name, an invalid email address, or a value outside an accepted range.
ASP.NET Core MVC already supports structured validation responses through ValidationProblemDetails.
Consider the following request model:
using System.ComponentModel.DataAnnotations;
public sealed class CreateCustomerRequest
{
[Required]
[StringLength(100)]
public string Name { get; set; } = string.Empty;
[Required]
[EmailAddress]
public string Email { get; set; } = string.Empty;
}
A controller can use the model:
[ApiController]
[Route("api/customers")]
public sealed class CustomersController : ControllerBase
{
[HttpPost]
public IActionResult Create(CreateCustomerRequest request)
{
return Created(
"/api/customers/10",
new { Id = 10, request.Name, request.Email });
}
}
Because the controller uses [ApiController], ASP.NET Core automatically checks model validation before executing the action. If validation fails, it returns HTTP 400 with a ValidationProblemDetails response.
For example:
{
"type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"errors": {
"Name": [
"The Name field is required."
],
"Email": [
"The Email field is not a valid e-mail address."
]
}
}
This is useful because validation failures already follow a structured format. Developers do not need to create a custom error object for every invalid request.
For manual validation failures, use ValidationProblem rather than returning an unrelated response shape:
if (!ModelState.IsValid)
{
return ValidationProblem(ModelState);
}
In a controller using [ApiController], this manual check is usually unnecessary because automatic validation handles it.
If the application needs to customize automatic validation responses, InvalidModelStateResponseFactory can be configured through ApiBehaviorOptions. This is useful when several APIs need consistent validation metadata or logging.
Use the Same Error Handling Approach Across Multiple APIs
The main benefit of ProblemDetails becomes clearer when an organization maintains several ASP.NET Core services.
Instead of copying the same exception handler and response customization into every project, move the shared error-handling components into a common class library.
A possible solution structure is:
Company.Services/
│
├── CustomerApi/
│ ├── Controllers/
│ └── Program.cs
│
├── OrderApi/
│ ├── Controllers/
│ └── Program.cs
│
├── PaymentApi/
│ ├── Controllers/
│ └── Program.cs
│
└── Company.ApiErrors/
├── ApiExceptionHandler.cs
├── ApiErrorExtensions.cs
└── Exceptions/
The shared library can expose an extension method:
public static class ApiErrorExtensions
{
public static IServiceCollection AddApiErrorHandling(
this IServiceCollection services,
string serviceName)
{
services.AddExceptionHandler<ApiExceptionHandler>();
services.AddProblemDetails(options =>
{
options.CustomizeProblemDetails = context =>
{
context.ProblemDetails.Extensions["traceId"] =
context.HttpContext.TraceIdentifier;
context.ProblemDetails.Extensions["service"] =
serviceName;
};
});
return services;
}
}
Each API can register the shared behavior with a different service name:
builder.Services.AddApiErrorHandling("CustomerApi");
The Order API can use:
builder.Services.AddApiErrorHandling("OrderApi");
And the Payment API can use:
builder.Services.AddApiErrorHandling("PaymentApi");
The middleware is then added to each application's pipeline:
app.UseExceptionHandler();
app.UseStatusCodePages();
This gives all services the same response structure and exception-mapping rules. If the organization later changes its error format or adds a new diagnostic property, the shared library can be updated instead of modifying every API independently.
In a larger system, avoid making the shared library responsible for every application's business exceptions. Common technical errors can be handled centrally, while each API can extend the approach with its own business-specific mappings.
Use ProblemDetails With Minimal APIs
ProblemDetails is not limited to controller-based applications. Minimal APIs can use the same service and middleware.
For example:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails();
var app = builder.Build();
app.UseExceptionHandler();
app.UseStatusCodePages();
app.MapGet("/customers/{id:int}", (int id) =>
{
if (id <= 0)
{
return Results.BadRequest();
}
if (id != 10)
{
return Results.NotFound();
}
return Results.Ok(new
{
Id = id,
Name = "John Smith"
});
});
app.Run();
The middleware can generate ProblemDetails responses for error results that do not already contain a response body.
For more specific business errors, Minimal API handlers can return typed ProblemDetails results or allow exceptions to reach the centralized exception handler. This keeps the error format consistent even when an organization uses controllers in one service and Minimal APIs in another.
In .NET 10, Minimal APIs also include built-in validation support through AddValidation. Validation failures can be integrated with the registered ProblemDetails service, allowing validation errors to follow the same response strategy.
Important Considerations for Production APIs
A consistent error format is useful only when the information inside it is reliable and safe.
The HTTP status code in the response body should match the actual HTTP response status. RFC 9457 explicitly requires this because HTTP clients and intermediaries rely on the status code independently of the response body.
The type property should identify a stable category of problem. Avoid creating a different type URI for every occurrence of the same error. A customer-not-found problem should use the same type identifier regardless of which customer was requested.
The title should describe the general problem, while detail should explain the specific occurrence. Clients should not parse the detail text to make application decisions. If a client needs a stable machine-readable error code, add an extension property such as code.
For example:
{
"type": "https://api.example.com/problems/duplicate-customer",
"title": "Duplicate customer",
"status": 409,
"detail": "A customer with the supplied email address already exists.",
"code": "CUSTOMER_ALREADY_EXISTS",
"traceId": "0HNA123456789:00000001"
}
Do not expose stack traces, SQL errors, internal file paths, or exception messages in production responses. These details can reveal information about the application's infrastructure and make security problems easier to exploit.
Also, do not convert every failure into HTTP 500. A missing resource, invalid request, authentication failure, and unexpected server exception represent different situations. Returning the correct status code helps clients decide whether to correct the request, authenticate again, retry, or contact support.
Finally, remember that not every response needs ProblemDetails. Successful responses should continue using their normal resource representations. ProblemDetails is intended for describing HTTP errors, not as a replacement for the application's regular response models.
Conclusion
Using ProblemDetails consistently makes ASP.NET Core APIs easier to consume, troubleshoot, and maintain. Instead of returning different error structures from every controller or service, applications can follow the common format defined by RFC 9457.
ASP.NET Core provides the building blocks through AddProblemDetails, IProblemDetailsService, IExceptionHandler, and ValidationProblemDetails. By placing shared error-handling components in a common library, teams can apply the same behavior across Customer API, Order API, Payment API, and other services.
The result is a predictable error contract for clients and a more manageable troubleshooting process for developers. It also allows individual APIs to retain their own business rules while following the same organization-wide approach to HTTP error responses.
Join the conversation! Your thoughts help the community grow.