.NET › Global Exception Handling & Middleware

What is the purpose of global exception handling middleware in an ASP.NET Core application?

Beginner

Answer

Global exception handling middleware catches unhandled exceptions thrown anywhere downstream in the pipeline (controllers, other middleware, business logic), preventing them from crashing the request or leaking a raw stack trace to clients, and instead converting them into a consistent, well-formed error response (like a standardized JSON error body with an appropriate HTTP status code) -- centralizing error-handling logic in one place instead of scattering try/catch blocks throughout every controller action.
app.UseExceptionHandler("/error");  // catches any unhandled exception from everything after this line

app.Map("/error", (HttpContext context) => {
    return Results.Problem(title: "An error occurred", statusCode: 500);
});
Real-world example Without global exception handling, a single unhandled null reference exception deep in business logic would return a raw ASP.NET Core error page (or worse, an unhandled crash) instead of the consistent JSON error format all API consumers expect.

Common follow-ups: How does UseExceptionHandler differ from the newer IExceptionHandler interface in .NET 8?;What information should and shouldn't be included in an error response for security reasons?