ASP.NET Core Interview Question #92
How can you implement global exception handling in modern ASP.NET Core?
Middleware & Request Pipeline Mid-Level Intermediate
Quick Interview Answer
Modern ASP.NET Core supports centralized exception handling through exception handling middleware and, in newer .NET versions, IExceptionHandler implementations.
Detailed Explanation
Modern ASP.NET Core supports centralized exception handling through exception handling middleware and, in newer .NET versions, IExceptionHandler implementations.
A global handler can translate known application exceptions into appropriate HTTP status codes and Problem Details responses while logging unexpected exceptions.
Centralized handling keeps repetitive try/catch blocks out of controllers. Business code should still catch exceptions when it can meaningfully recover, add required context, or perform compensating behavior.
Code Example
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
builder.Services.AddProblemDetails();
var app = builder.Build();
app.UseExceptionHandler();
public sealed class GlobalExceptionHandler : IExceptionHandler
{
public async ValueTask<bool> TryHandleAsync(
HttpContext httpContext,
Exception exception,
CancellationToken cancellationToken)
{
httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
await httpContext.Response.WriteAsJsonAsync(
new { error = "An unexpected error occurred." },
cancellationToken);
return true;
}
}