Resiliency: Error Handling and Logging

7 min read

Introduction

In the deterministic universe of computer science, the only certainty is that uncertainty exists. Systems fail, networks timeout, and inputs deviate from expectations.

Interesting Fact: The first computer "bug" was literally a moth found trapped in a relay of the Harvard Mark II computer in 1947 by Grace Hopper's team. We have been "debugging" ever since.

Resiliency in ASP.NET Core is not about preventing errors entirely—that is an impossible pursuit. Rather, it is about how gracefully your application fails, how securely it communicates that failure to the user, and how meticulously it records the event for analysis.

This guide explores the standard mechanisms for catching exceptions and the art of structured logging.


1. Catching It All: Global Exception Handling 🕸️

Definition

An Exception is an event that disrupts the normal flow of the program's instructions. Global Exception Handling is a centralized mechanism to intercept these disruptions at the application boundary (Middleware) before they crash the server or return a generic HTTP 500 response.

The Problem

Beginners often wrap individual blocks of code in try-catch statements.

csharp
// The "Anti-Pattern"
public IActionResult GetData() {
    try {
        // ... logic
    } catch (Exception ex) {
        return StatusCode(500, "Something went wrong");
    }
}

If you have 50 controllers, you will repeat this logic 50 times. This violates the DRY (Don't Repeat Yourself) principle and makes changing error policies impossible. Furthermore, it clutters business logic with infrastructure concerns.

The Solution: Middleware & IExceptionHandler

ASP.NET Core uses a middleware pipeline. By placing an error-handling middleware at the start of the pipeline, we can catch exceptions thrown by any subsequent part of the application.

As of .NET 8, the industry standard is to use the IExceptionHandler interface combined with ProblemDetails.

Implementation

Step 1: Create the Exception Handler
This class determines how to translate a C# exception into an HTTP response.

csharp
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;

public class GlobalExceptionHandler : IExceptionHandler
{
    private readonly ILogger<GlobalExceptionHandler> _logger;

    public GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger)
    {
        _logger = logger;
    }

    public async ValueTask<bool> TryHandleAsync(
        HttpContext httpContext,
        Exception exception,
        CancellationToken cancellationToken)
    {
        _logger.LogError(
            exception, 
            "An unhandled exception has occurred: {Message}", 
            exception.Message
        );

        var problemDetails = new ProblemDetails
        {
            Status = StatusCodes.Status500InternalServerError,
            Title = "Server Error",
            Detail = "An internal error occurred. Please try again later."
        };

        httpContext.Response.StatusCode = problemDetails.Status.Value;

        await httpContext.Response
            .WriteAsJsonAsync(problemDetails, cancellationToken);

        // Return true to signal the exception is handled
        return true; 
    }
}

Step 2: Register Services in Program.cs

csharp
// Add services to the container
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
builder.Services.AddProblemDetails(); // Standardizes error format (RFC 7807)

Step 3: Configure Pipeline

csharp
var app = builder.Build();

// This must be one of the first middlewares
app.UseExceptionHandler(); 

app.Run();

2. Developer Exception Page vs. Secure Production Error Pages 🚦

Definition

Environment Configuration allows an application to behave differently based on where it is running (Localhost/Development vs. Server/Production).

The Problem

When an error occurs during development, you need the Stack Trace—the precise list of method calls that led to the crash.
However, displaying a stack trace in production is a Critical Security Vulnerability. It reveals database structures, file paths, and framework versions to potential attackers.

The Solution

ASP.NET Core provides the IWebHostEnvironment interface to toggle behavior.

Implementation

In your Program.cs, you explicitly define two different paths.

csharp
var app = builder.Build();

// Check if we are in 'Development' environment
if (app.Environment.IsDevelopment())
{
    // Shows detailed stack traces, headers, and cookies
    // Commonly referred to as the "Yellow Screen of Death" descendant
    app.UseDeveloperExceptionPage(); 
    
    // Or simpler: swagger is usually dev only
    app.UseSwagger();
    app.UseSwaggerUI();
}
else
{
    // Production settings
    // Redirects to the global handler defined in Topic 1
    app.UseExceptionHandler("/Error");
    
    // Adds HTTP Strict Transport Security headers
    app.UseHsts(); 
}

Note: The UseDeveloperExceptionPage is automatically enabled in Development environment in recent .NET versions, but knowing how to control it explicitly is required for custom scenarios.


3. Leaving a Trail: Using the Built-in ILogger 🪵

Definition

Logging is the practice of recording system events. ILogger is the built-in abstraction in ASP.NET Core that allows you to write logs without worrying about where they are stored (Console, File, Cloud).

The Problem

Developers often use Console.WriteLine("Error happened").

  1. It is synchronous and hurts performance.
  2. It has no "severity" level (everything looks the same).
  3. It cannot be easily toggled off in production.

The Solution

Use Dependency Injection (DI) to inject ILogger<T>.

Log Levels

Understanding severity is crucial for filtering noise.

  1. Trace (0): Secrets, extremely detailed info.
  2. Debug (1): Internal variable states during development.
  3. Information (2): General flow ("User X logged in").
  4. Warning (3): Something unexpected but recoverable (Disk running low).
  5. Error (4): Operation failed (Database timeout).
  6. Critical (5): Application crash (Out of memory).

Implementation

csharp
[ApiController]
[Route("[controller]")]
public class ProductsController : ControllerBase
{
    // T is the class name, used to categorize the logs
    private readonly ILogger<ProductsController> _logger;

    public ProductsController(ILogger<ProductsController> logger)
    {
        _logger = logger;
    }

    [HttpGet("{id}")]
    public IActionResult GetProduct(int id)
    {
        // ❌ Bad Practice: String Interpolation
        // _logger.LogInformation($"Fetching product {id}"); 
        // Why? It creates a string in memory even if logging is disabled.

        // ✅ Best Practice: Structured Logging Templates
        _logger.LogInformation("Fetching product {ProductId} at {Time}", id, DateTime.UtcNow);

        try 
        {
            // Simulate logic
            if (id < 0) throw new ArgumentException("Invalid ID");
            return Ok();
        }
        catch (Exception ex)
        {
            // Always pass the exception object first
            _logger.LogError(ex, "Failed to get product {ProductId}", id);
            return BadRequest();
        }
    }
}

4. Structured Logging: Integrating Serilog 📝

Definition

Structured Logging saves log entries as objects (JSON) rather than plain text strings. Serilog is the most popular third-party logging library for .NET that replaces the built-in logger to provide advanced capabilities.

The Problem

If you log to a text file: [Info] User 42 bought Item 99.
If you want to ask: "How many times did User 42 buy something?", you have to use Regex or grep tools. This is slow and error-prone.

The Solution

With Structured Logging, the log is stored as:

json
{
  "Level": "Information",
  "Message": "User 42 bought Item 99",
  "Properties": {
    "UserId": 42,
    "ItemId": 99
  }
}

You can now query this data in tools like Seq, Elasticsearch, or Datadog like a database: select * where UserId == 42.

Implementation: Serilog

Step 1: Install Packages

bash
dotnet add package Serilog.AspNetCore
dotnet add package Serilog.Sinks.Console

Step 2: Configuration (Program.cs)
Serilog is unique because it should ideally start before the Host starts, to catch startup errors.

csharp
using Serilog;

// Configuration
Log.Logger = new LoggerConfiguration()
    .WriteTo.Console()
    .CreateLogger();

try {
    Log.Information("Starting web application");

    var builder = WebApplication.CreateBuilder(args);

    // Swap the default logger with Serilog
    builder.Host.UseSerilog((context, services, configuration) => configuration
        .ReadFrom.Configuration(context.Configuration) // Read settings from appsettings.json
        .ReadFrom.Services(services)
        .Enrich.FromLogContext()
        .WriteTo.Console());

    var app = builder.Build();

    // Adds middleware to log HTTP requests automatically
    // (logs method, path, status code, timing)
    app.UseSerilogRequestLogging(); 

    app.MapGet("/", () => "Hello Serilog!");

    app.Run();
}
catch (Exception ex)
{
    Log.Fatal(ex, "Application terminated unexpectedly");
}
finally
{
    Log.CloseAndFlush();
}

Step 3: AppSettings.json
Control logging without recompiling code.

json
{
  "Serilog": {
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning", 
        "System": "Warning"
      }
    }
  }
}

Note: We override "Microsoft" to "Warning" to prevent ASP.NET Core from flooding our console with internal noise, keeping our logs clean.


Summary

  1. Global Handling: Never use try-catch for generic server errors. Use IExceptionHandler.
  2. Environment: Show details to developers, hide details from the public.
  3. ILogger: Use the abstraction. Avoid string interpolation in log messages.
  4. Serilog: Upgrade to structured logging for any serious production application to enable querying.

References & Further Reading

Challenge

Task

You are tasked with implementing a robust resiliency strategy for an ASP.NET Core application. Your goal is to create a global exception handler and configure the application's pipeline to behave differently in Development versus other environments.

Requirements

  1. Create a Global Exception Handler:

    • Define a public class named ProductionExceptionHandler that implements the IExceptionHandler interface.
    • The class should accept an ILogger<ProductionExceptionHandler> through its constructor and store it in a private readonly field.
    • Implement the TryHandleAsync method.
      • Inside the method, log the exception at the Error level. Use the following structured logging template: "An unexpected error occurred: {Message}", passing the exception's message as the parameter.
      • Set the HttpContext.Response.StatusCode to 500 (Internal Server Error).
      • Write a standard ProblemDetails object to the response body. This object must have the following properties:
        • Status: 500
        • Type: "https://tools.ietf.org/html/rfc7231#section-6.6.1"
        • Title: "An unexpected error occurred."
      • The method must return a ValueTask<bool> that evaluates to true, indicating the exception has been successfully handled.
  2. Configure Program.cs:

    • In the service registration section, add the services required for your custom exception handler and for ProblemDetails to function correctly.
    • In the middleware pipeline configuration section, add logic to use the DeveloperExceptionPage only when the application is running in the Development environment.
    • For all other environments, configure the pipeline to use the global exception handler middleware.

Expected result

Your final code should consist of a fully implemented ProductionExceptionHandler class and the correct service and middleware registrations in the Program.cs section.

ProductionExceptionHandler.cs

csharp
public class ProductionExceptionHandler : IExceptionHandler
{
    private readonly ILogger<ProductionExceptionHandler> _logger;

    public ProductionExceptionHandler(ILogger<ProductionExceptionHandler> logger)
    {
        _logger = logger;
    }

    public async ValueTask<bool> TryHandleAsync(
        HttpContext httpContext,
        Exception exception,
        CancellationToken cancellationToken)
    {
        _logger.LogError(exception, "An unexpected error occurred: {Message}", exception.Message);

        httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;

        await httpContext.Response.WriteAsJsonAsync(new ProblemDetails
        {
            Status = StatusCodes.Status500InternalServerError,
            Type = "https://tools.ietf.org/html/rfc7231#section-6.6.1",
            Title = "An unexpected error occurred."
        }, cancellationToken);

        return true;
    }
}

Program.cs Configuration

csharp
// Service Registrations
builder.Services.AddExceptionHandler<ProductionExceptionHandler>();
builder.Services.AddProblemDetails();

// Middleware Pipeline Configuration
if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseExceptionHandler(); 
}
csharp

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.