Introduction
One of the characteristics of a professional API is how it responds when something goes wrong. Returning a raw stack trace to the client creates a security risk. Adding separate try-catch blocks to every controller creates duplicated code, inconsistent status codes, and maintenance problems.
In this lesson, we will create a centralized error-handling mechanism for our ASP.NET Core application. We will distinguish expected application errors, validation failures, and unexpected system errors. Each error type will then be mapped to an appropriate HTTP status code and returned in a consistent Problem Details format.
Problem Details is a standard format for producing machine-readable error documents in HTTP APIs. A typical response may contain type, title, status, detail, and instance members. ASP.NET Core provides built-in building blocks such as AddProblemDetails, UseExceptionHandler, and IExceptionHandler.
Where error handling belongs in the architecture
From a Clean Architecture perspective, producing an exception and converting that exception into an HTTP response are different responsibilities. The Domain or Application layer may throw a meaningful exception when a business rule is violated. However, translating that exception into a 404, 409, or 422 response belongs to the Presentation/API layer.
- Domain: Can produce domain exceptions when invariant business rules are violated.
- Application: Can produce application exceptions when a resource is missing or a use case cannot continue.
- Infrastructure: Can produce technical exceptions related to databases, external services, or the file system.
- Presentation/API: Catches exceptions, logs them, and converts them into HTTP Problem Details responses.
This separation keeps the Application layer independent from ASP.NET Core and HTTP concepts. For example, throwing a NotFoundException from the Application layer is preferable to calling NotFound() or BadRequest() there.
Defining known error types
Let us first create a shared exception base in the Application layer. These classes represent expected errors that can safely be communicated to the client.
namespace Catalog.Application.Common.Exceptions;
public abstract class ApplicationException : Exception
{
protected ApplicationException(string message) : base(message)
{
}
}
public sealed class NotFoundException : ApplicationException
{
public NotFoundException(string resourceName, object key)
: base($"{resourceName} with key '{key}' was not found.")
{
}
}
public sealed class ConflictException : ApplicationException
{
public ConflictException(string message) : base(message)
{
}
}
public sealed class ValidationException : ApplicationException
{
public IReadOnlyDictionary<string, string[]> Errors { get; }
public ValidationException(
IReadOnlyDictionary<string, string[]> errors)
: base("One or more validation errors occurred.")
{
Errors = errors;
}
}These exceptions carry safe messages intended for the API contract. By contrast, technical details from a SqlException, NullReferenceException, or file access failure should not be sent directly to the client.
Enabling the Problem Details service
Register the Problem Details services in Program.cs. The Customize callback is useful for adding a trace identifier to every error response. This identifier allows support teams to correlate a client response with server-side logs without exposing implementation details.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddProblemDetails(options =>
{
options.CustomizeProblemDetails = context =>
{
context.ProblemDetails.Extensions["traceId"] =
context.HttpContext.TraceIdentifier;
};
});
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
var app = builder.Build();
app.UseExceptionHandler();
app.UseHttpsRedirection();
app.MapControllers();
app.Run();AddProblemDetails registers the default Problem Details service. AddExceptionHandler registers our custom handler with the dependency injection container. UseExceptionHandler should run early in the pipeline so it can observe exceptions thrown by controllers, application services, or infrastructure components.
Creating a global handler with IExceptionHandler
In modern ASP.NET Core applications, implementing IExceptionHandler is a clean alternative to writing one large custom middleware class. The TryHandleAsync method processes an exception and returns true when a response has been produced successfully.
using Catalog.Application.Common.Exceptions;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
public sealed class GlobalExceptionHandler : IExceptionHandler
{
private readonly ILogger<GlobalExceptionHandler> _logger;
public GlobalExceptionHandler(
ILogger<GlobalExceptionHandler> logger)
{
_logger = logger;
}
public async ValueTask<bool> TryHandleAsync(
HttpContext httpContext,
Exception exception,
CancellationToken cancellationToken)
{
var traceId = httpContext.TraceIdentifier;
if (exception is ApplicationException)
{
_logger.LogWarning(
exception,
"Handled application error. TraceId: {TraceId}",
traceId);
}
else
{
_logger.LogError(
exception,
"Unhandled server error. TraceId: {TraceId}",
traceId);
}
var problemDetails = CreateProblemDetails(
httpContext,
exception,
traceId);
httpContext.Response.StatusCode = problemDetails.Status ?? 500;
await httpContext.Response.WriteAsJsonAsync(
problemDetails,
cancellationToken);
return true;
}
private static ProblemDetails CreateProblemDetails(
HttpContext context,
Exception exception,
string traceId)
{
var problem = exception switch
{
NotFoundException notFound => new ProblemDetails
{
Status = StatusCodes.Status404NotFound,
Title = "Resource not found",
Detail = notFound.Message,
Type = "https://httpstatuses.com/404"
},
ConflictException conflict => new ProblemDetails
{
Status = StatusCodes.Status409Conflict,
Title = "Conflict",
Detail = conflict.Message,
Type = "https://httpstatuses.com/409"
},
ValidationException validation => new ProblemDetails
{
Status = StatusCodes.Status422UnprocessableEntity,
Title = "Validation failed",
Detail = validation.Message,
Type = "https://httpstatuses.com/422"
},
_ => new ProblemDetails
{
Status = StatusCodes.Status500InternalServerError,
Title = "An unexpected error occurred",
Detail = "The request could not be completed.",
Type = "https://httpstatuses.com/500"
}
};
problem.Instance = context.Request.Path;
problem.Extensions["traceId"] = traceId;
if (exception is ValidationException validationException)
{
problem.Extensions["errors"] = validationException.Errors;
}
return problem;
}
}The status-related type URIs above are included as simple examples. In a real project, define stable problem type URIs owned by your application and point them to useful documentation. Notice also that the real message from an unexpected exception is not placed in Detail in production.
Examining the response format
An Application service can throw an exception when a product cannot be found:
public async Task<ProductDto> GetByIdAsync(
Guid id,
CancellationToken cancellationToken)
{
var product = await _productRepository
.GetByIdAsync(id, cancellationToken);
if (product is null)
{
throw new NotFoundException("Product", id);
}
return _mapper.Map<ProductDto>(product);
}The client receives a predictable response:
HTTP/1.1 404 Not Found
Content-Type: application/problem+json
{
"type": "https://httpstatuses.com/404",
"title": "Resource not found",
"status": 404,
"detail": "Product with key '...' was not found.",
"instance": "/api/products/...",
"traceId": "00-..."
}This format means that a frontend or another API client does not have to parse only a human-readable message. The status, type, and documented extension properties can be processed reliably by software.
Validation errors and the difference between 400 and 422
A malformed request and a business rule violation are not necessarily the same thing. Missing required fields or sending text where a number is expected are usually treated as 400 Bad Request. FluentValidation failures can also be returned as 400 if that is the convention selected for the project.
If the request is syntactically readable but its values cannot be processed according to the application rules, 422 Unprocessable Content may be appropriate. The most important principle is consistency across the API. Ensure that controller-level validation and the global exception handler do not generate two different responses for the same failure.
When should you use a custom middleware?
A custom middleware can perform the same task. It surrounds the call to next(context) with a try-catch block and writes the response when an exception occurs. This approach is simple and flexible, but the middleware can become large as the number of exception types grows.
The IExceptionHandler approach makes it easier to separate handlers and manage them through dependency injection. A small application may be perfectly comfortable with one middleware. In a larger system, separating handlers by exception category or bounded context can improve maintainability.
Common mistakes
- Returning stack traces: File paths, SQL details, and class names may be exposed in production.
- Returning 400 for every exception: This prevents clients from distinguishing client errors from server failures.
- Repeating try-catch blocks in controllers: Error handling becomes duplicated and loses its centralized nature.
- Skipping server-side logging: Even when only a safe response is returned, the exception and trace ID should be logged.
- Treating exception messages as the API contract: Clients should rely on status, type, and documented extensions rather than changeable natural-language text.
- Throwing after the response has started: The status code may no longer be changeable once the response body has begun.
Practice exercise
- Create an
UnauthorizedApplicationExceptionorForbiddenExceptionin the Application layer. - Map the exception to status code 401 or 403 in the global handler.
- Throw the exception from a controller endpoint and inspect the response in Swagger or an HTTP client.
- Add a
traceIdand, if useful, anerrorCodeextension property to the response. - Trigger an unexpected
InvalidOperationExceptionand verify that the real exception message is not sent to the client.
Conclusion
In this lesson, we standardized API error behavior by creating centralized exception handling. The Application layer produces meaningful exceptions, while the Presentation layer performs the HTTP-specific translation. Known failures are represented with appropriate 4xx responses, and unexpected failures are returned as safe 500 responses.
Problem Details gives clients a consistent contract for processing errors and allows developers to correlate client-visible failures with server logs through a trace ID. In the next stages, this error contract can be extended alongside authentication, authorization, and API documentation.