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 true
Layer |
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);
}
}
Join the conversation! Your thoughts help the community grow.