Building robust and production-ready ASP.NET Core Web API applications requires a consistent and centralized error handling strategy. In real-world enterprise applications, unhandled exceptions can lead to inconsistent HTTP responses, security vulnerabilities, and poor client experience. Implementing Global Exception Handling in ASP.NET Core ensures structured error responses, proper HTTP status codes, and better observability across distributed systems.
In this article, we will explore how to implement global exception handling in ASP.NET Core Web API using Middleware and the built-in exception handling mechanisms.
Why Global Exception Handling is Important
In ASP.NET Core Web API development, exceptions can occur due to validation failures, database errors, business rule violations, or unexpected runtime failures. Without a centralized exception handling mechanism:
Controllers become cluttered with try-catch blocks.
Error responses become inconsistent.
Sensitive information may leak in production.
Logging and monitoring become fragmented.
Global exception handling solves these problems by intercepting all unhandled exceptions in a single place and returning standardized JSON error responses.
Default Exception Handling in ASP.NET Core
ASP.NET Core provides built-in support through the UseExceptionHandler middleware. In development, the Developer Exception Page displays detailed stack traces. However, in production environments, we should never expose internal exception details.
Basic configuration in Program.cs:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/error");
}
app.MapControllers();
app.Run();
This approach redirects exceptions to a specific endpoint. While useful, it is limited for advanced API scenarios. A custom middleware approach gives full control.
Implementing Custom Global Exception Middleware
Creating a custom middleware is the recommended enterprise approach for global exception handling in ASP.NET Core Web API.
Step 1: Create Exception Middleware
using System.Net;
using System.Text.Json;
public class GlobalExceptionMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<GlobalExceptionMiddleware> _logger;
public GlobalExceptionMiddleware(RequestDelegate next, ILogger<GlobalExceptionMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
_logger.LogError(ex, "Unhandled exception occurred.");
await HandleExceptionAsync(context, ex);
}
}
private static Task HandleExceptionAsync(HttpContext context, Exception exception)
{
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
var response = new
{
StatusCode = context.Response.StatusCode,
Message = "An unexpected error occurred.",
Detailed = exception.Message
};
var jsonResponse = JsonSerializer.Serialize(response);
return context.Response.WriteAsync(jsonResponse);
}
}
Step 2: Register Middleware in Program.cs
Join the conversation! Your thoughts help the community grow.