Recipe 5.4 · C#
Global Exception Handling with ProblemDetails
- Problem
- The way it's often written
- The improved recipe
- How it works
- Variations and pitfalls
- On .NET Framework
Problem
Every controller action has its own try/catch that logs and returns a hand-built error
object. The shapes differ between endpoints, some return HTML error pages to API clients, and a
few return the full exception text, connection string fragment included.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
// Not this: the same try/catch pasted into every action.
public ActionResult GetCustomer(int id)
{
try
{
return Json(_service.Get(id));
}
catch (Exception ex)
{
LogHelper.Error("GetCustomer", ex);
return Json(new { success = false, error = ex.ToString() });
}
}
The improved recipe
Handle exceptions in one place with IExceptionHandler (ASP.NET Core 8 and later) and return RFC
9457 ProblemDetails JSON. Map the exceptions from Recipe 5.3 to status codes there.
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace ImproveCode.Errors;
public sealed class AppExceptionHandler(
IProblemDetailsService problemDetails,
IHostEnvironment environment,
ILogger<AppExceptionHandler> logger) : IExceptionHandler
{
public async ValueTask<bool> TryHandleAsync(
HttpContext context, Exception exception, CancellationToken ct)
{
(int status, string title) = exception switch
{
NotFoundException => (404, "Not found"),
ConflictException => (409, "Conflict"),
BusinessRuleException => (422, "Business rule violated"),
_ => (500, "An unexpected error occurred")
};
if (status >= 500)
{
logger.LogError(exception,
"Unhandled exception on {Method} {Path}",
context.Request.Method, context.Request.Path);
}
else
{
logger.LogInformation(
"Request failed with {Status}: {Message}",
status, exception.Message);
}
var problem = new ProblemDetails
{
Status = status,
Title = title,
Instance = context.Request.Path,
// Only messages written for users are shown.
Detail = exception is AppException ? exception.Message : null
};
problem.Extensions["traceId"] = context.TraceIdentifier;
if (exception is AppException app)
{
problem.Extensions["errorCode"] = app.ErrorCode;
}
if (status >= 500 && environment.IsDevelopment())
{
problem.Detail = exception.ToString();
}
context.Response.StatusCode = status;
return await problemDetails.TryWriteAsync(new ProblemDetailsContext
{
HttpContext = context,
ProblemDetails = problem,
Exception = exception
});
}
}
public static class ErrorHandlingSetup
{
public static IServiceCollection AddAppErrorHandling(
this IServiceCollection services)
{
services.AddProblemDetails();
services.AddExceptionHandler<AppExceptionHandler>();
return services;
}
public static IApplicationBuilder UseAppErrorHandling(
this IApplicationBuilder app)
{
app.UseExceptionHandler(); // runs registered IExceptionHandlers
app.UseStatusCodePages(); // ProblemDetails for bare 404s etc.
return app;
}
}
In Program.cs, as a usage snippet:
builder.Services.AddAppErrorHandling();
WebApplication app = builder.Build();
app.UseAppErrorHandling(); // first in the pipeline
app.UseCorrelationId(); // Chapter 4, Recipe 4.3
A request for a missing customer now returns:
{
"type": "https://tools.ietf.org/html/rfc9110#section-15.5.5",
"title": "Not found",
"status": 404,
"detail": "Customer '42' was not found.",
"instance": "/customers/42",
"traceId": "4bf92f3577b34da6a3ce929d0e0e4736",
"errorCode": "not_found"
}
How it works
UseExceptionHandler() with no arguments catches any exception that escapes the rest of the
pipeline and passes it to each registered IExceptionHandler in order until one returns true.
Actions and services can now just throw. The per-action try/catch blocks go away, and so do
the inconsistent error shapes.
The switch expression is the whole policy in a few lines. Expected failures get a 4xx status and their message. Everything else gets a 500 with a generic title and no detail, because an unknown exception's message may contain anything. In Development the full exception text is included so you don't have to dig through logs on your own machine.
Only 500s are logged as errors. A 404 for a missing record is a normal outcome, and logging it at
Error floods dashboards and trains people to ignore red. The traceId is the correlation ID
from Chapter 4, so a support call that starts with "my reference is 4bf92f..." leads straight to
the request's log lines.
IProblemDetailsService.TryWriteAsync writes application/problem+json, fills in the standard
type link for the status code, and respects any customization registered with
AddProblemDetails. UseStatusCodePages gives bare status results (a 404 from routing, a 405)
the same JSON shape.
Variations and pitfalls
- Register it first in the pipeline so it also catches failures in other middleware.
- For MVC or Razor Pages apps that serve HTML, the same handler works. Check the
Acceptheader and redirect to an error page that displays thetraceId, or useUseExceptionHandler("/Error")for browser routes. - If the response has already started (a streaming download failed halfway), nothing can change the status code. The handler still logs; the client sees a truncated response.
- You can register several handlers, for example one for
DbUpdateConcurrencyExceptionthat returns 409, before the general one. They run in registration order. - Don't map
ArgumentExceptionto 400 globally. AnArgumentExceptiondeep in your code is usually a bug, not bad client input. Validate input at the boundary (Chapter 8) instead.
On .NET Framework
ASP.NET MVC 5 and Web API 2 offer HandleErrorAttribute, ExceptionFilterAttribute and
IExceptionHandler (in System.Web.Http.ExceptionHandling). The same mapping logic fits in a Web
API ExceptionHandler subclass registered with
config.Services.Replace(typeof(IExceptionHandler), ...). For Web Forms, Application_Error in
Global.asax is the single place to log and redirect.