When an unhandled exception occurs inside an ASP.NET Core MVC controller, action filter, endpoint, or middleware component, scattering try/catch blocks across every action creates inconsistent error shapes, duplicated logging logic, and risk of leaking internal stack traces or sensitive diagnostics to callers. Conversely, relying solely on an MVC filter misses exceptions thrown outside MVC—such as in authentication/rate-limiting middleware, model binding/endpoint routing, or background request delegates.
ASP.NET Core's IExceptionHandler pipeline paired with AddProblemDetails() and UseExceptionHandler() solves this uniformly across the entire request pipeline. Multiple IExceptionHandler implementations execute in registration order: each handler inspects Exception and returns ValueTask<bool>—returning true when it has handled and written the RFC 9457 application/problem+json response, or false to pass the exception down to the next handler in the chain (and ultimately to the default ProblemDetails fallback).
1. Architectural Blueprint & Exception Handler Chain
Plaintext
Exception thrown in MVC Controller, Filter, or Middleware
│
▼
[UseExceptionHandler()] intercepts unhandled exception
│
├─> Handler 1: DomainExceptionHandler (IExceptionHandler)
│ ├─ Matches known domain/business exceptions?
│ │ ├─ Yes ──> Maps to status code (404 / 409 / 422), writes RFC 9457 ProblemDetails, returns true
│ │ └─ No ──> Logs trace context & returns false (chains to next handler)
│ ▼
├─> Handler 2: ValidationAndArgumentExceptionHandler (IExceptionHandler)
│ ├─ Matches ArgumentException / ArgumentOutOfRangeException / KeyNotFoundException?
│ │ ├─ Yes ──> Maps to 400 / 404 ProblemDetails, returns true
│ │ └─ No ──> Returns false
│ ▼
└─> Handler 3 (Fallback): UnhandledServerExceptionHandler (IExceptionHandler)
├─ Logs structured error with traceId
└─ Writes 500 Internal Server Error ProblemDetails (safe message) & returns trueLayer |
Responsibility |
Key Benefit |
Chained |
Each handler owns a clear exception category and returns |
Keeps error-mapping rules modular, testable, and easy to extend without giant |
RFC 9457 |
Emits standard |
Gives API and MVC clients a predictable, machine-readable |
Pipeline-Wide Coverage |
Triggered by |
Prevents inconsistent error formats between MVC actions and cross-cutting middleware. |
2. Domain Exceptions and Chained IExceptionHandler Implementations
Let's define a crisp set of domain exceptions (EntityNotFoundException, ConflictOperationException, BusinessRuleViolationException) and three chained IExceptionHandler classes registered in order:
DomainExceptionHandler— handles domain-specific exceptions (404,409,422).InputExceptionHandler— handles standard argument/lookup exceptions (400,404).FallbackProblemDetailsHandler— handles any remaining unexpected exception (500) with safe error details and correlation metadata.
C#
using System.Diagnostics;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
public abstract class DomainException : Exception
{
public string ErrorCode { get; }
protected DomainException(string errorCode, string message)
: base(message)
{
ErrorCode = errorCode;
}
}
public sealed class EntityNotFoundException : DomainException
{
public EntityNotFoundException(string errorCode, string message)
: base(errorCode, message)
{
}
}
public sealed class ConflictOperationException : DomainException
{
public ConflictOperationException(string errorCode, string message)
: base(errorCode, message)
{
}
}
public sealed class BusinessRuleViolationException : DomainException
{
public BusinessRuleViolationException(string errorCode, string message)
: base(errorCode, message)
{
}
}
internal static class ProblemDetailsFactoryHelper
{
public static ProblemDetails Create(
HttpContext httpContext,
int statusCode,
string typeUri,
string title,
string detail,
string? errorCode = null)
{
string traceId = Activity.Current?.TraceId.ToString() ?? httpContext.TraceIdentifier;
var problem = new ProblemDetails
{
Status = statusCode,
Type = typeUri,
Title = title,
Detail = detail,
Instance = httpContext.Request.Path.Value
};
problem.Extensions["traceId"] = traceId;
if (!string.IsNullOrWhiteSpace(errorCode))
{
problem.Extensions["errorCode"] = errorCode;
}
return problem;
}
public static async ValueTask<bool> WriteProblemAsync(
HttpContext httpContext,
IProblemDetailsService problemDetailsService,
ProblemDetails problemDetails,
CancellationToken cancellationToken)
{
httpContext.Response.StatusCode = problemDetails.Status ?? StatusCodes.Status500InternalServerError;
httpContext.Response.ContentType = "application/problem+json";
return await problemDetailsService.TryWriteAsync(new ProblemDetailsContext
{
HttpContext = httpContext,
ProblemDetails = problemDetails
});
}
}
public sealed class DomainExceptionHandler : IExceptionHandler
{
private readonly IProblemDetailsService _problemDetailsService;
private readonly ILogger<DomainExceptionHandler> _logger;
public DomainExceptionHandler(
IProblemDetailsService problemDetailsService,
ILogger<DomainExceptionHandler> logger)
{
_problemDetailsService = problemDetailsService;
_logger = logger;
}
public async ValueTask<bool> TryHandleAsync(
HttpContext httpContext,
Exception exception,
CancellationToken cancellationToken)
{
if (exception is not DomainException domainException)
{
// Pass to the next handler in the IExceptionHandler chain
return false;
}
(int statusCode, string typeUri, string title) = domainException switch
{
EntityNotFoundException => (
StatusCodes.Status404NotFound,
"https://problems.example.local/errors/resource-not-found",
"Resource Not Found"),
ConflictOperationException => (
StatusCodes.Status409Conflict,
"https://problems.example.local/errors/conflict",
"Conflict Detected"),
BusinessRuleViolationException => (
StatusCodes.Status422UnprocessableEntity,
"https://problems.example.local/errors/business-rule-violation",
"Business Rule Violation"),
_ => (
StatusCodes.Status400BadRequest,
"https://problems.example.local/errors/domain-error",
"Domain Error")
};
_logger.LogWarning(
domainException,
"Domain exception {ErrorCode} mapped to HTTP {StatusCode} on {Path}.",
domainException.ErrorCode,
statusCode,
httpContext.Request.Path);
ProblemDetails problem = ProblemDetailsFactoryHelper.Create(
httpContext,
statusCode,
typeUri,
title,
domainException.Message,
domainException.ErrorCode);
return await ProblemDetailsFactoryHelper.WriteProblemAsync(
httpContext,
_problemDetailsService,
problem,
cancellationToken);
}
}
public sealed class InputExceptionHandler : IExceptionHandler
{
private readonly IProblemDetailsService _problemDetailsService;
private readonly ILogger<InputExceptionHandler> _logger;
public InputExceptionHandler(
IProblemDetailsService problemDetailsService,
ILogger<InputExceptionHandler> logger)
{
_problemDetailsService = problemDetailsService;
_logger = logger;
}
public async ValueTask<bool> TryHandleAsync(
HttpContext httpContext,
Exception exception,
CancellationToken cancellationToken)
{
if (exception is not (ArgumentException or KeyNotFoundException))
{
return false;
}
int statusCode = exception is KeyNotFoundException
? StatusCodes.Status404NotFound
: StatusCodes.Status400BadRequest;
string typeUri = statusCode == StatusCodes.Status404NotFound
? "https://problems.example.local/errors/not-found"
: "https://problems.example.local/errors/invalid-argument";
string title = statusCode == StatusCodes.Status404NotFound
? "Not Found"
: "Invalid Input";
_logger.LogInformation(
exception,
"Input exception {ExceptionType} mapped to HTTP {StatusCode} on {Path}.",
exception.GetType().Name,
statusCode,
httpContext.Request.Path);
ProblemDetails problem = ProblemDetailsFactoryHelper.Create(
httpContext,
statusCode,
typeUri,
title,
exception.Message,
errorCode: exception.GetType().Name.ToUpperInvariant());
return await ProblemDetailsFactoryHelper.WriteProblemAsync(
httpContext,
_problemDetailsService,
problem,
cancellationToken);
}
}
public sealed class FallbackProblemDetailsHandler : IExceptionHandler
{
private readonly IProblemDetailsService _problemDetailsService;
private readonly ILogger<FallbackProblemDetailsHandler> _logger;
public FallbackProblemDetailsHandler(
IProblemDetailsService problemDetailsService,
ILogger<FallbackProblemDetailsHandler> logger)
{
_problemDetailsService = problemDetailsService;
_logger = logger;
}
public async ValueTask<bool> TryHandleAsync(
HttpContext httpContext,
Exception exception,
CancellationToken cancellationToken)
{
_logger.LogError(
exception,
"Unhandled exception {ExceptionType} on {Path}.",
exception.GetType().Name,
httpContext.Request.Path);
ProblemDetails problem = ProblemDetailsFactoryHelper.Create(
httpContext,
StatusCodes.Status500InternalServerError,
"https://problems.example.local/errors/internal-server-error",
"Internal Server Error",
"An unexpected fault occurred while processing the request.",
errorCode: "INTERNAL_ERROR");
return await ProblemDetailsFactoryHelper.WriteProblemAsync(
httpContext,
_problemDetailsService,
problem,
cancellationToken);
}
}3. MVC Controller Demonstrating Chained Exception Handling
Notice how OrdersController does not catch domain or unexpected exceptions locally; it lets them propagate naturally into the IExceptionHandler chain, where each handler maps them to a consistent ProblemDetails response.
C#
using Microsoft.AspNetCore.Mvc;
public sealed record CancelOrderRequest(
string OrderId,
string Reason,
bool SimulateUnexpectedFault = false
);
public sealed record CancelOrderResponse(
string OrderId,
string Status,
string Reason
);
[ApiController]
[Route("api/orders")]
public sealed class OrdersController : ControllerBase
{
[HttpPost("cancel")]
public IActionResult Cancel([FromBody] CancelOrderRequest request)
{
if (request is null || string.IsNullOrWhiteSpace(request.OrderId))
{
throw new ArgumentException("OrderId is required to cancel an order.", nameof(request.OrderId));
}
if (request.SimulateUnexpectedFault)
{
throw new InvalidOperationException("Simulated downstream gateway failure.");
}
if (string.Equals(request.OrderId, "ORD-404", StringComparison.OrdinalIgnoreCase))
{
throw new EntityNotFoundException(
errorCode: "ORDER_NOT_FOUND",
message: $"Order '{request.OrderId}' does not exist.");
}
if (string.Equals(request.OrderId, "ORD-LOCKED", StringComparison.OrdinalIgnoreCase))
{
throw new ConflictOperationException(
errorCode: "ORDER_ALREADY_DISPATCHED",
message: $"Order '{request.OrderId}' has already been dispatched and cannot be cancelled.");
}
if (string.IsNullOrWhiteSpace(request.Reason) || request.Reason.Trim().Length < 5)
{
throw new BusinessRuleViolationException(
errorCode: "CANCELLATION_REASON_TOO_SHORT",
message: "Cancellation reason must be at least 5 characters long.");
}
return Ok(new CancelOrderResponse(
OrderId: request.OrderId.Trim().ToUpperInvariant(),
Status: "Cancelled",
Reason: request.Reason.Trim()));
}
}4. Wiring AddProblemDetails, Chained IExceptionHandlers, and UseExceptionHandler in Program.cs
The order in which AddExceptionHandler<T>() is called defines the execution order of the chain: DomainExceptionHandler runs first, then InputExceptionHandler, and finally FallbackProblemDetailsHandler. Placing app.UseExceptionHandler() early in the middleware pipeline ensures both middleware and MVC actions share the exact same ProblemDetails error format.
C#
using Microsoft.AspNetCore.Mvc;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails(options =>
{
options.CustomizeProblemDetails = context =>
{
context.ProblemDetails.Instance ??= context.HttpContext.Request.Path.Value;
context.ProblemDetails.Extensions.TryAdd("traceId", context.HttpContext.TraceIdentifier);
};
});
// Chain order: 1) Domain -> 2) Input -> 3) Fallback (500)
builder.Services.AddExceptionHandler<DomainExceptionHandler>();
builder.Services.AddExceptionHandler<InputExceptionHandler>();
builder.Services.AddExceptionHandler<FallbackProblemDetailsHandler>();
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Intercepts exceptions across middleware and MVC controllers
app.UseExceptionHandler();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllers();
app.Run();
public partial class Program { }5. End-to-End Integration Testing with WebApplicationFactory<Program>
Testing against WebApplicationFactory<Program> confirms that each exception type flows through its matching handler in the IExceptionHandler chain and returns RFC 9457 application/problem+json with the expected HTTP status code, errorCode, and traceId.
C#
using System.Net;
using System.Net.Http.Json;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;
public sealed class ExceptionHandlerChainIntegrationTests : IClassFixture<WebApplicationFactory<Program>>
{
private readonly WebApplicationFactory<Program> _factory;
public ExceptionHandlerChainIntegrationTests(WebApplicationFactory<Program> factory)
{
_factory = factory;
}
[Fact]
public async Task CancelOrder_WhenOrderNotFound_Returns404DomainProblemDetails()
{
using HttpClient client = _factory.CreateClient();
HttpResponseMessage response = await client.PostAsJsonAsync(
"/api/orders/cancel",
new CancelOrderRequest("ORD-404", "Customer requested cancellation"));
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
ProblemDetails? problem = await response.Content.ReadFromJsonAsync<ProblemDetails>();
Assert.NotNull(problem);
Assert.Equal(StatusCodes.Status404NotFound, problem.Status);
Assert.Equal("Resource Not Found", problem.Title);
Assert.True(problem.Extensions.ContainsKey("errorCode"));
Assert.Equal("ORDER_NOT_FOUND", problem.Extensions["errorCode"]?.ToString());
Assert.True(problem.Extensions.ContainsKey("traceId"));
}
[Fact]
public async Task CancelOrder_WhenOrderAlreadyDispatched_Returns409ConflictProblemDetails()
{
using HttpClient client = _factory.CreateClient();
HttpResponseMessage response = await client.PostAsJsonAsync(
"/api/orders/cancel",
new CancelOrderRequest("ORD-LOCKED", "Duplicate order"));
Assert.Equal(HttpStatusCode.Conflict, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
ProblemDetails? problem = await response.Content.ReadFromJsonAsync<ProblemDetails>();
Assert.NotNull(problem);
Assert.Equal(StatusCodes.Status409Conflict, problem.Status);
Assert.Equal("ORDER_ALREADY_DISPATCHED", problem.Extensions["errorCode"]?.ToString());
}
[Fact]
public async Task CancelOrder_WhenUnexpectedFaultOccurs_Returns500SafeProblemDetails()
{
using HttpClient client = _factory.CreateClient();
HttpResponseMessage response = await client.PostAsJsonAsync(
"/api/orders/cancel",
new CancelOrderRequest("ORD-100", "Valid reason", SimulateUnexpectedFault: true));
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
ProblemDetails? problem = await response.Content.ReadFromJsonAsync<ProblemDetails>();
Assert.NotNull(problem);
Assert.Equal(StatusCodes.Status500InternalServerError, problem.Status);
Assert.Equal("INTERNAL_ERROR", problem.Extensions["errorCode"]?.ToString());
Assert.DoesNotContain("Simulated downstream gateway failure", problem.Detail ?? string.Empty);
}
}6. Conclusion
Chaining custom IExceptionHandler implementations with AddProblemDetails() and UseExceptionHandler() gives ASP.NET Core MVC applications a clean, composable, and uniform error-handling pipeline across both MVC actions and middleware. Each handler focuses on a specific exception tier, returns true or false to control chain propagation, attaches correlation metadata (traceId and errorCode), and emits RFC 9457 application/problem+json responses without leaking internal fault details.

Join the conversation! Your thoughts help the community grow.