Error Handling in ASP.NET Core

What is Error Handling?

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.

  • Global Exception Handling: Manage unhandled exceptions in one place.
  • Custom Error Pages: Show user-friendly error messages.
  • Detailed Error Logs: Log detailed error information for developers.

Configuring Global Error Handling

1. Use the 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.

2. Configure Developer Exception Page

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.


Implementing Centralized Exception Handling

1. Create a Custom Middleware


// 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.

2. Register the Middleware


// Program.cs
app.UseMiddleware<ErrorHandlingMiddleware>();

                

Add the custom middleware to the request pipeline.


Logging Errors

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.


Key Benefits of Proper Error Handling

  • User Experience: Provide user-friendly error messages.
  • Application Stability: Prevent crashes and maintain uptime.
  • Debugging: Detailed error logs help developers identify and fix issues.