Handling Global Exceptions in .NET Core is very important in real-world applications to avoid duplicate try-catch blocks and centralize error handling.
In ASP.NET Core / .NET Core, there are 3 common ways to handle Global Exceptions:
✅ 1. Using Global Exception Middleware (Recommended — Most Common)
This is the best and cleanest approach.
Step 1: Create Global Exception Middleware
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, "Something went wrong");
context.Response.StatusCode = 500;
context.Response.ContentType = "application/json";
var response = new
{
Message = "Internal Server Error",
Details = ex.Message
};
await context.Response.WriteAsJsonAsync(response);
}
}
}
Step 2: Register Middleware in Program.cs
(.NET 6 / .NET 7 / .NET 8)
app.UseMiddleware<GlobalExceptionMiddleware>();
Place it before other middleware:
var app = builder.Build();
app.UseMiddleware<GlobalExceptionMiddleware>();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
✅ Why Middleware is Best
✔ Centralized error handling
✔ Clean Controllers
✔ Logging support
✔ Custom error responses
✔ Production friendly
✅ Example Controller (No Try-Catch Needed)
[HttpGet]
public IActionResult Get()
{
throw new Exception("Something broke");
}
Output
{
"message": "Internal Server Error",
"details": "Something broke"
}
✅ 2. Using Built-in Exception Handler (Simple Method)
.NET Core has built-in exception handling:
app.UseExceptionHandler("/error");
Create Controller:
[Route("/error")]
public IActionResult HandleError()
{
return Problem("Something went wrong");
}
✅ 3. Using Exception Filters (MVC Only)
Create Filter:
public class GlobalExceptionFilter : IExceptionFilter
{
public void OnException(ExceptionContext context)
{
context.Result = new ObjectResult("Something went wrong")
{
StatusCode = 500
};
}
}
Register:
builder.Services.AddControllers(options =>
{
options.Filters.Add<GlobalExceptionFilter>();
});
🏆 Interview Best Answer
If interviewer asks:
How do you handle global exceptions in .NET Core?
You can say:
"I handle global exceptions using custom middleware in ASP.NET Core.
The middleware catches all unhandled exceptions, logs them, and returns standardized error responses. This helps maintain clean controllers and centralized error handling."
Real-World Best Practice
Use this combination:
✔ Global Middleware
✔ ILogger logging
✔ Custom Error Response Model
✔ Different handling for Dev vs Production
Example:
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseMiddleware<GlobalExceptionMiddleware>();
}
Pro Level (Production Ready Response Model)
Create Error Response Model
public class ErrorResponse
{
public string Message { get; set; }
public int StatusCode { get; set; }
public string TraceId { get; set; }
}
Summary
| Method | Recommended | Use Case |
|---|---|---|
| Middleware | ⭐ Best | Production apps |
| Built-in Handler | Good | Simple apps |
| Exception Filter | OK | MVC only |
