Error handling in ASP.NET Core ensures that errors and exceptions are gracefully managed and meaningful information is returned to the client. It improves application stability and provides better user experiences.
UseExceptionHandler
Middleware
Add the UseExceptionHandler
middleware in your Program.cs
file to handle exceptions globally.
// Program.cs
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.MapGet("/", () => throw new Exception("An error occurred!"));
app.Map("/Error", () => Results.Problem("An unexpected error occurred."));
app.Run();
When an exception occurs, users are redirected to the /Error
endpoint.
In development, enable the Developer Exception Page to display detailed error information.
// Program.cs
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
This helps developers debug errors during development.
// Middleware/ErrorHandlingMiddleware.cs
public class ErrorHandlingMiddleware
{
private readonly RequestDelegate _next;
public ErrorHandlingMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private static Task HandleExceptionAsync(HttpContext context, Exception exception)
{
context.Response.ContentType = "application/json";
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
return context.Response.WriteAsync(new
{
StatusCode = context.Response.StatusCode,
Message = "Internal Server Error. Please try again later.",
Details = exception.Message
}.ToString());
}
}
The middleware catches exceptions and returns a JSON response with error details.
// Program.cs
app.UseMiddleware<ErrorHandlingMiddleware>();
Add the custom middleware to the request pipeline.
Logging is critical for diagnosing issues in production. ASP.NET Core provides built-in logging functionality.
// Program.cs
builder.Logging.AddConsole();
try
{
var app = builder.Build();
app.Run();
}
catch (Exception ex)
{
Console.WriteLine($"Application startup failed: {ex.Message}");
}
Use the built-in logging providers to capture error details.