Introduction
Error handling is an important part of building reliable ASP.NET Core applications. Every application needs a consistent way to handle unexpected exceptions, return meaningful HTTP responses, and provide enough information for developers to investigate problems.
Consider an ASP.NET Core API that retrieves customer information from a database. Everything works normally until a database connection fails. The application throws an exception, but the API does not handle it properly. The client may receive an unexpected response, an empty error message, or a generic HTTP 500 response without useful information.
A common approach is to use exception-handling middleware to catch unhandled exceptions and return a structured error response.
ASP.NET Core supports the Problem Details format, which provides a standard structure for communicating HTTP API errors. Instead of returning different error formats from different endpoints, an application can return consistent responses containing information such as the HTTP status code, error title, detail, and request location.
However, implementing centralized error handling requires some care. Middleware should not hide the original exception, replace useful error information with a generic message, or expose sensitive internal details to clients.
For example, an application may catch a database exception and return a message such as "Something went wrong." This protects internal information, but developers still need the original exception, stack trace, and related diagnostic details to identify the actual problem.
The correct implementation should provide a safe error response to the client while preserving the original exception for logging and troubleshooting.
In this article, we will understand Problem Details, explore ASP.NET Core exception-handling middleware, implement centralized error handling, preserve original exceptions, handle custom exceptions, and configure consistent error responses for production applications.
Understanding Problem Details
Problem Details is a standardized format for describing errors returned by HTTP APIs.
It is defined by RFC 9457, which supersedes RFC 7807.
The purpose of Problem Details is to provide a consistent structure for API errors. Clients can understand the general error information without depending on a different response format for every endpoint.
A Problem Details response commonly contains the following properties:
Property | Purpose |
|---|
type | Identifies the type of problem, usually through a URI |
title | Provides a short description of the problem |
status | Contains the HTTP status code |
detail | Provides additional information about the specific problem |
instance | Identifies the particular occurrence of the problem |
For example, an API may return the following response when a requested customer does not exist:
{
"type": "https://example.com/problems/customer-not-found",
"title": "Customer not found",
"status": 404,
"detail": "The requested customer could not be found.",
"instance": "/api/customers/105"
}
The response tells the client that the requested resource does not exist.
The type property identifies the category of problem, while title provides a short description. The status property contains the HTTP response status code.
The detail property provides information about the specific occurrence, and instance identifies the request that caused the problem.
Problem Details can also contain additional properties when an application needs to provide structured information beyond the standard fields.
For example, a validation error response may include an errors property containing field-level validation messages.
The important point is that Problem Details provides a common error response structure. It does not automatically determine how an application should handle every exception. Developers still need to decide how exceptions are logged, which HTTP status codes should be returned, and what information is safe to expose.
Why Centralized Exception Handling Is Important
Without centralized exception handling, developers may write separate try-catch blocks in every controller or endpoint.
For example:
app.MapGet("/api/customers/{id}", async (int id) =>
{
try
{
var customer = await GetCustomerAsync(id);
return Results.Ok(customer);
}
catch (Exception)
{
return Results.Problem(
title: "Something went wrong.",
statusCode: 500);
}
});
The same pattern may appear in multiple endpoints.
This creates several problems.
First, developers need to maintain similar error-handling code in different places. If the response format changes, multiple endpoints may need updates.
Second, some endpoints may return different error structures because developers handle exceptions differently.
Third, developers may accidentally catch exceptions without logging them. The client receives an error response, but the development team loses the information required to investigate the failure.
Centralized exception-handling middleware solves these problems by providing one location for handling unhandled exceptions across the request pipeline.
The middleware can identify the exception, log the original error, determine the appropriate HTTP status code, and return a Problem Details response.
This allows application endpoints to focus on business logic rather than repeating the same exception-handling code.
Understanding ASP.NET Core Middleware
Middleware components are part of the ASP.NET Core request processing pipeline.
Each middleware component can perform work before and after the next component executes.
A simplified request pipeline looks like this:
Incoming HTTP Request
|
v
Exception Middleware
|
v
Authentication
|
v
Authorization
|
v
API Endpoint
|
v
Application Logic
|
v
HTTP Response
Exception-handling middleware is usually placed early in the request pipeline so that it can observe exceptions thrown by later middleware components and endpoints.
If an endpoint throws an exception, the exception travels back through the middleware pipeline.
The exception-handling middleware can catch it and generate an appropriate HTTP response.
However, middleware cannot catch an exception that occurs outside the portion of the pipeline it wraps. This is one reason why middleware registration order matters.
Step 1. Create an ASP.NET Core Web API Project
Let's create a sample application that returns Problem Details responses when an unexpected exception occurs.
Open a terminal and execute:
dotnet new webapi -n ProblemDetailsMiddlewareDemo
Navigate to the project directory:
cd ProblemDetailsMiddlewareDemo
Open the project in Visual Studio or Visual Studio Code.
For this example, we will create endpoints that retrieve customer information and demonstrate how exceptions are handled centrally.
Step 2. Configure Problem Details Services
ASP.NET Core provides built-in support for generating Problem Details responses.
Register the service in Program.cs:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails();
var app = builder.Build();
app.Run();
The AddProblemDetails method registers the services required to generate Problem Details responses.
This registration makes the Problem Details service available through dependency injection and supports integration with ASP.NET Core error-handling components.
However, registering the service alone does not automatically catch every exception in the application.
We still need to configure exception-handling middleware.
Step 3. Add Exception-Handling Middleware
ASP.NET Core provides UseExceptionHandler for centralized exception handling.
Update Program.cs:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails();
var app = builder.Build();
app.UseExceptionHandler();
app.MapGet("/api/customers/{id}", (int id) =>
{
if (id <= 0)
{
throw new ArgumentException(
"Customer ID must be greater than zero.");
}
throw new InvalidOperationException(
"Unable to retrieve customer information.");
});
app.Run();
The UseExceptionHandler middleware catches unhandled exceptions that occur later in the request pipeline.
When an exception occurs, ASP.NET Core attempts to produce an error response using the configured exception-handling services.
Because AddProblemDetails is registered, the framework can generate a Problem Details response when the response has not already started and the request is eligible for handling.
This approach is useful because developers do not need to write the same exception-handling logic in every endpoint.
For example, if the customer endpoint throws an InvalidOperationException, the exception-handling middleware can return a structured HTTP 500 response instead of allowing the exception to escape as an unhandled server error.
The actual response depends on the registered Problem Details services, the environment, and any additional configuration.
For production applications, we should also configure logging and control which exception details are returned to clients.
Step 4. Understand the Difference Between the Original Exception and the Error Response
One of the most important parts of centralized error handling is preserving the original exception.
Consider this code:
try
{
await ProcessOrderAsync();
}
catch (Exception ex)
{
throw new Exception("Order processing failed.");
}
This code catches the original exception and creates a new exception.
The problem is that the new exception does not preserve the original exception as its inner exception.
The original failure may have contained important information, such as a database connection error or an invalid operation.
After creating a new exception without retaining the original one, developers may lose useful diagnostic context.
A better approach is to preserve the original exception:
try
{
await ProcessOrderAsync();
}
catch (Exception ex)
{
throw new Exception(
"Order processing failed.",
ex);
}
The original exception is now available through the InnerException property.
However, wrapping an exception is not always necessary.
If the application only needs to log the exception and allow the original failure to continue through the exception-handling middleware, use throw without creating another exception.
try
{
await ProcessOrderAsync();
}
catch (Exception ex)
{
logger.LogError(
ex,
"Order processing failed.");
throw;
}
The throw statement preserves the original exception and its stack trace.
Avoid using throw ex because it resets the stack trace information associated with the exception.
In most cases, centralized middleware should handle unexpected exceptions. Business services should catch exceptions only when they can take meaningful action, add useful context, or translate a known failure into a specific application exception.
Step 5. Access the Original Exception Through Middleware
ASP.NET Core provides IExceptionHandler for implementing custom exception-handling logic.
This interface allows developers to create a dedicated handler that receives information about an exception and decides whether it has handled the failure.
Create a class named GlobalExceptionHandler:
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
public class GlobalExceptionHandler : IExceptionHandler
{
private readonly ILogger<GlobalExceptionHandler> logger;
public GlobalExceptionHandler(
ILogger<GlobalExceptionHandler> logger)
{
this.logger = logger;
}
public async ValueTask<bool> TryHandleAsync(
HttpContext httpContext,
Exception exception,
CancellationToken cancellationToken)
{
logger.LogError(
exception,
"Unhandled exception occurred. TraceId: {TraceId}",
httpContext.TraceIdentifier);
var problemDetails = new ProblemDetails
{
Status = StatusCodes.Status500InternalServerError,
Title = "An unexpected error occurred.",
Detail = "The server could not complete the request.",
Instance = httpContext.Request.Path
};
problemDetails.Extensions["traceId"] =
httpContext.TraceIdentifier;
httpContext.Response.StatusCode =
StatusCodes.Status500InternalServerError;
await httpContext.Response.WriteAsJsonAsync(
problemDetails,
cancellationToken);
return true;
}
}
Let's understand this implementation.
The class implements IExceptionHandler, which allows ASP.NET Core to invoke the custom handler when an unhandled exception occurs.
The TryHandleAsync method receives three important values.
The HttpContext represents the current HTTP request and response.
The Exception parameter contains the original exception that caused the failure.
The CancellationToken allows the handler to observe cancellation while writing the response.
The logger records the exception using LogError.
Passing the exception object to LogError is important because the logging provider can capture its message, stack trace, and inner exception information.
The handler then creates a ProblemDetails object containing a safe message for the client.
The traceId extension property contains the request trace identifier. This helps developers correlate the error response with server-side logs.
Finally, the handler writes the response and returns true to indicate that the exception has been handled.
Notice that the original exception is not replaced or modified. It is passed directly to the logger, while the client receives a separate Problem Details response.
This separation is important. The client receives a safe error description, while the development team retains the original diagnostic information in the server logs.
Step 6. Register the Custom Exception Handler
After creating GlobalExceptionHandler, register it in Program.cs.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails();
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
var app = builder.Build();
app.UseExceptionHandler();
app.MapGet("/api/customers/{id}", (int id) =>
{
if (id <= 0)
{
throw new ArgumentException(
"Customer ID must be greater than zero.");
}
throw new InvalidOperationException(
"Unable to retrieve customer information.");
});
app.Run();
The AddExceptionHandler method registers the custom handler with dependency injection.
The UseExceptionHandler middleware activates centralized exception handling.
When an unhandled exception occurs, ASP.NET Core invokes registered IExceptionHandler implementations.
The GlobalExceptionHandler receives the original exception, logs it, and returns a Problem Details response.
This approach keeps exception-handling logic outside controllers and endpoints.
For applications with multiple exception handlers, ASP.NET Core invokes them in registration order until one reports that it handled the exception.
This allows developers to create specialized handlers for different exception types.
Step 7. Preserve the Original Exception When Creating Custom Exceptions
In real applications, developers often create custom exceptions to represent business failures.
For example, an order service may throw an OrderNotFoundException when the requested order does not exist.
Create a custom exception:
public class OrderNotFoundException : Exception
{
public OrderNotFoundException(int orderId)
: base($"Order with ID {orderId} was not found.")
{
OrderId = orderId;
}
public int OrderId { get; }
}
This exception provides a specific representation of a business condition.
Now consider a service that retrieves an order from a database:
public async Task<Order> GetOrderAsync(
int orderId,
CancellationToken cancellationToken)
{
try
{
var order = await repository.GetByIdAsync(
orderId,
cancellationToken);
if (order is null)
{
throw new OrderNotFoundException(orderId);
}
return order;
}
catch (SqlException ex)
{
throw new InvalidOperationException(
"Unable to retrieve the order from the database.",
ex);
}
}
The service creates an OrderNotFoundException when the order does not exist.
If the database operation fails with a SqlException, the service wraps the original database exception inside an InvalidOperationException.
This preserves the database exception as the inner exception.
However, developers should avoid wrapping exceptions unnecessarily. If a service does not need to change the exception type or add meaningful context, allowing the original exception to propagate is usually better.
Also, an expected business condition such as a missing order does not always need to be represented by an exception. Returning a result type or a nullable value may be more appropriate depending on the application design.
The important point is to distinguish expected business outcomes from unexpected application failures.
Step 8. Return Different Problem Details Responses for Different Exceptions
Not every exception should result in HTTP 500.
For example:
OrderNotFoundException should normally return HTTP 404.
ValidationException may return HTTP 400.
UnauthorizedAccessException may require HTTP 403, depending on the application's authentication and authorization design.
Unexpected database or application failures may return HTTP 500.
A custom exception handler can map known exceptions to appropriate HTTP status codes.
Update GlobalExceptionHandler:
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
public class GlobalExceptionHandler : IExceptionHandler
{
private readonly ILogger<GlobalExceptionHandler> logger;
public GlobalExceptionHandler(
ILogger<GlobalExceptionHandler> logger)
{
this.logger = logger;
}
public async ValueTask<bool> TryHandleAsync(
HttpContext httpContext,
Exception exception,
CancellationToken cancellationToken)
{
var statusCode = exception switch
{
OrderNotFoundException =>
StatusCodes.Status404NotFound,
ArgumentException =>
StatusCodes.Status400BadRequest,
_ =>
StatusCodes.Status500InternalServerError
};
logger.LogError(
exception,
"Request failed with status code {StatusCode}. TraceId: {TraceId}",
statusCode,
httpContext.TraceIdentifier);
var problemDetails = new ProblemDetails
{
Status = statusCode,
Title = statusCode switch
{
404 => "Order not found.",
400 => "Invalid request.",
_ => "An unexpected error occurred."
},
Detail = statusCode == 500
? "The server could not complete the request."
: exception.Message,
Instance = httpContext.Request.Path
};
problemDetails.Extensions["traceId"] =
httpContext.TraceIdentifier;
httpContext.Response.StatusCode = statusCode;
await httpContext.Response.WriteAsJsonAsync(
problemDetails,
cancellationToken);
return true;
}
}
The switch expression maps known exception types to HTTP status codes.
For an OrderNotFoundException, the handler returns HTTP 404.
For an ArgumentException, it returns HTTP 400.
For other exceptions, it returns HTTP 500.
The Detail property is also handled differently depending on the exception type.
For known client-related errors, the application may return a safe and useful message. For unexpected server errors, it returns a generic message.
This prevents internal exception details from being exposed to API consumers.
One important consideration is that ArgumentException should not automatically be treated as a client error in every application. An ArgumentException may indicate a programming defect inside the server rather than invalid client input.
A more reliable production design uses specific application exceptions for known client errors instead of mapping broad framework exception types without considering their source.
Step 9. Use a Dedicated Exception for Validation Failures
Validation failures are common in APIs.
For example, an application may reject an order when the quantity is zero or the customer ID is missing.
ASP.NET Core can return validation errors using Problem Details with an errors extension.
A simple validation exception can be created as follows:
public class RequestValidationException : Exception
{
public RequestValidationException(
IDictionary<string, string[]> errors)
: base("One or more validation errors occurred.")
{
Errors = errors;
}
public IDictionary<string, string[]> Errors { get; }
}
The exception stores validation errors by field.
Now update the handler to support it:
if (exception is RequestValidationException validationException)
{
var validationProblem = new ValidationProblemDetails(
validationException.Errors)
{
Status = StatusCodes.Status400BadRequest,
Title = "One or more validation errors occurred.",
Instance = httpContext.Request.Path
};
validationProblem.Extensions["traceId"] =
httpContext.TraceIdentifier;
httpContext.Response.StatusCode =
StatusCodes.Status400BadRequest;
await httpContext.Response.WriteAsJsonAsync(
validationProblem,
cancellationToken);
return true;
}
ValidationProblemDetails is designed specifically for validation failures.
For example, the response may look like this:
{
"type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"errors": {
"Quantity": [
"Quantity must be greater than zero."
],
"CustomerId": [
"Customer ID is required."
]
},
"traceId": "00-abc123-example"
}
The errors property contains validation messages associated with individual fields.
This makes it easier for frontend applications to display the correct message beside each input field.
In production applications, validation is often better handled through dedicated validation components or endpoint filters. However, a consistent Problem Details format should still be used when returning validation failures.
Step 10. Use Built-In Exception Handling for Production Applications
ASP.NET Core provides built-in exception-handling middleware that can be configured without implementing every response manually.
For example:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails();
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler();
}
app.MapGet("/api/orders/{id}", (int id) =>
{
throw new InvalidOperationException(
"Order processing failed.");
});
app.Run();
The exception handler is enabled outside the Development environment.
This is important because development and production environments have different diagnostic requirements.
During development, developers need detailed exception information to identify problems quickly.
In production, exposing stack traces, database details, file paths, or internal implementation information can create security risks.
The application should return a safe Problem Details response to clients while recording the original exception through server-side logging.
If a custom IExceptionHandler is registered, it can be used with the same built-in middleware.
The built-in middleware is generally preferable to writing custom middleware from scratch unless the application has a specific requirement that the framework does not cover.
Step 11. Understand Why Middleware Registration Order Matters
Middleware order affects which exceptions can be handled centrally.
Consider this configuration:
app.UseExceptionHandler();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
The exception-handling middleware is placed before authentication, authorization, and controller execution.
This allows it to observe exceptions thrown by those later components.
Now consider the opposite arrangement:
app.UseAuthentication();
app.UseAuthorization();
app.UseExceptionHandler();
app.MapControllers();
In this arrangement, exceptions thrown by authentication or authorization middleware occur before the exception-handling middleware has been reached.
The exception handler cannot catch exceptions that occur outside the portion of the pipeline it wraps.
For this reason, exception-handling middleware should normally be registered early in the request pipeline.
There are also other important middleware considerations.
For example, if a response has already started, the application may not be able to replace it with a Problem Details response. The response headers or body may already have been sent to the client.
A centralized exception handler should therefore check whether the response has started before attempting to write a new error response.
Step 12. Avoid Exposing Sensitive Exception Details
One of the most common mistakes in error handling is returning the original exception message directly to the client.
Consider this exception:
SqlException:
Login failed for user 'app_user'.
Server=production-sql.internal;
Database=CustomerDatabase;
Returning this information to an API consumer can expose internal infrastructure details.
A better response is:
{
"title": "An unexpected error occurred.",
"status": 500,
"detail": "The server could not complete the request.",
"traceId": "00-abc123-example"
}
The server logs should contain the original exception, including its stack trace and inner exception information.
The client receives only the information required to understand that the operation failed.
A trace identifier provides a way to connect the client-visible error with the corresponding server-side log entry.
Developers can search the logs using the trace identifier without exposing internal diagnostic information through the public API.
Step 13. Handle Exceptions When the Response Has Already Started
Exception-handling middleware cannot always replace an existing response.
Consider an API that streams a large file to a client.
The application begins writing the response body. After several chunks have been sent, a database or file operation fails.
At this point, the response has already started.
The middleware cannot safely change the response status code to HTTP 500 or replace the partially transmitted file with a Problem Details document.
A custom exception handler should account for this condition.
For example:
public async ValueTask<bool> TryHandleAsync(
HttpContext httpContext,
Exception exception,
CancellationToken cancellationToken)
{
if (httpContext.Response.HasStarted)
{
logger.LogError(
exception,
"An exception occurred after the response started.");
return false;
}
logger.LogError(
exception,
"Unhandled exception occurred.");
var problemDetails = new ProblemDetails
{
Status = StatusCodes.Status500InternalServerError,
Title = "An unexpected error occurred.",
Detail = "The server could not complete the request."
};
httpContext.Response.StatusCode =
StatusCodes.Status500InternalServerError;
await httpContext.Response.WriteAsJsonAsync(
problemDetails,
cancellationToken);
return true;
}
If the response has already started, the handler logs the original exception and returns false.
Returning false indicates that this handler did not handle the exception. Other registered handlers may be given an opportunity to process it.
However, once the response has started, another handler generally cannot replace the response with a new Problem Details document either.
This is why streaming endpoints and long-running responses need their own failure-handling design.
Step 14. Add Trace IDs for Easier Troubleshooting
A trace identifier helps developers connect an API response with server-side logs.
ASP.NET Core provides HttpContext.TraceIdentifier, which identifies the current request within the application.
The custom exception handler already uses this value:
problemDetails.Extensions["traceId"] =
httpContext.TraceIdentifier;
The same identifier is also written to the log:
logger.LogError(
exception,
"Unhandled exception occurred. TraceId: {TraceId}",
httpContext.TraceIdentifier);
Suppose a client reports an error and provides this trace identifier:
TraceId: 0HXYZ123456789
A developer can search the application logs for that value and locate the corresponding exception.
For distributed applications, Activity.Current?.TraceId can provide a distributed tracing identifier when an activity is available.
A trace identifier and a distributed trace ID serve related but different purposes. HttpContext.TraceIdentifier identifies the request within the ASP.NET Core application, while the distributed trace ID can connect operations across multiple services.
For applications using OpenTelemetry, distributed trace context is especially useful because it allows developers to follow a request across service boundaries.
Testing Problem Details Responses
Error handling should be tested just like any other application functionality.
A successful API request does not prove that exception-handling middleware works correctly.
You should test different scenarios, including:
An unexpected exception returns HTTP 500.
A missing resource returns HTTP 404.
A validation failure returns HTTP 400.
The response uses the expected Problem Details structure.
The trace identifier is included in the response.
The original exception is logged.
Internal exception details are not exposed to clients.
Exceptions occurring after the response starts are handled appropriately.
For example, you can use curl to test an endpoint:
curl -i https://localhost:7001/api/customers/0
A correctly configured application should return an appropriate HTTP error response.
You can also write integration tests using WebApplicationFactory from Microsoft.AspNetCore.Mvc.Testing.
For example:
[Fact]
public async Task UnexpectedException_ReturnsProblemDetails()
{
var response = await client.GetAsync(
"/api/test/throw");
Assert.Equal(
HttpStatusCode.InternalServerError,
response.StatusCode);
Assert.Equal(
"application/problem+json",
response.Content.Headers.ContentType?.MediaType);
var problem = await response.Content
.ReadFromJsonAsync<ProblemDetails>();
Assert.NotNull(problem);
Assert.Equal(
StatusCodes.Status500InternalServerError,
problem.Status);
}
This test sends a request to an endpoint designed to throw an exception.
It verifies that the application returns HTTP 500 and uses the Problem Details media type.
The test also reads the response into a ProblemDetails object and verifies the status code.
For this test, the application should expose a test endpoint such as /api/test/throw that deliberately throws an exception. Such endpoints should exist only in the test environment and must not be exposed in production.
Common Mistakes When Implementing Problem Details Middleware
Mistake | Why It Causes Problems | Recommended Solution |
|---|
Catching exceptions without logging them | The original failure becomes difficult to investigate | Log the exception object with structured logging |
Creating a new exception without the original as InnerException | Important diagnostic information may be lost | Use throw or preserve the original exception as the inner exception |
Using throw ex | The original stack trace may be reset | Use throw when rethrowing the same exception |
Returning exception messages directly | May expose database, server, or infrastructure details | Return safe client-facing messages |
Registering exception middleware too late | Earlier middleware failures may not be caught | Place exception handling early in the pipeline |
Returning HTTP 500 for every error | Clients cannot distinguish missing resources from server failures | Map known application exceptions to appropriate status codes |
Writing an error response after the response has started | The response cannot safely be replaced | Check Response.HasStarted and handle streaming failures separately |
Returning different error formats | Clients need separate parsing logic for each endpoint | Use a consistent Problem Details structure |
Logging the same exception repeatedly | Creates duplicate log entries and makes troubleshooting harder | Define clear ownership of exception logging |
Exposing detailed errors in production | May reveal sensitive implementation details | Use generic responses and keep diagnostic details in server logs |
Best Practices for Handling Exceptions in ASP.NET Core
Use Built-In Exception-Handling Middleware
Prefer the built-in UseExceptionHandler middleware for centralized exception handling.
It integrates with ASP.NET Core and supports custom IExceptionHandler implementations.
Writing custom middleware is not necessary for most applications. Use it only when the application needs behavior that the built-in exception-handling components cannot provide.
Preserve the Original Exception
Always preserve the original exception when logging or translating an error.
Pass the original exception object to the logger so that stack traces and inner exceptions are available.
When wrapping an exception, use the constructor that accepts the original exception as the inner exception.
Avoid creating new exceptions that discard the original failure details.
Separate Expected Business Errors From Unexpected Failures
A missing customer or invalid order is usually an expected application condition.
A database connection failure or unexpected NullReferenceException is generally an unexpected failure.
Handle known business conditions with appropriate status codes and messages. Do not treat every exception as an internal server error.
Also avoid using broad exception types as a substitute for a well-defined application error model.
Use Safe Error Messages
Clients should receive enough information to understand the failure, but they should not receive internal stack traces, connection strings, SQL statements, or sensitive infrastructure details.
Use generic messages for unexpected server errors.
Store the original exception in server-side logs for investigation.
Include Trace Identifiers
Add a trace identifier to Problem Details responses where appropriate.
This gives API consumers a reference they can provide to the development team when reporting an issue.
For distributed applications, use distributed tracing to connect related operations across services.
Keep Logging Consistent
Centralized middleware should be responsible for logging unhandled exceptions.
Avoid logging the same exception at every layer unless each log adds meaningful information.
Use structured logging with properties such as trace ID, request path, exception type, and status code.
This makes logs easier to search and analyze.
Handle Response-Started Scenarios
Some endpoints stream files, server-sent events, or large responses.
The application may not be able to return Problem Details after response transmission has started.
Check the response state and design streaming endpoints to handle failures appropriately.
Test Error Responses in Every Environment
Test error handling in development, testing, and production-like environments.
Verify that detailed diagnostic information is available to developers but is not exposed to public API consumers.
Also verify that the application returns consistent status codes and response formats.
Summary
Problem Details provides a standard way to communicate errors from ASP.NET Core APIs. When combined with centralized exception-handling middleware, it helps applications return consistent error responses without repeating exception-handling logic in every endpoint.
In this article, we explored how to configure AddProblemDetails, use UseExceptionHandler, implement IExceptionHandler, preserve original exceptions, map custom exceptions to HTTP status codes, and return validation errors.
We also discussed middleware registration order, response-started scenarios, trace identifiers, logging, and security considerations.
The most important principle is to separate the error information returned to clients from the diagnostic information needed by developers.
Clients should receive safe and meaningful Problem Details responses. Server-side logs should preserve the original exception, stack trace, and relevant diagnostic context.
A well-designed exception-handling strategy makes an ASP.NET Core API easier to maintain, troubleshoot, and integrate with other applications.
Join the conversation! Your thoughts help the community grow.