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.
// 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.
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
// Add services to the container
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
builder.Services.AddProblemDetails(); // Standardizes error format (RFC 7807)Step 3: Configure Pipeline
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.
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").
- It is synchronous and hurts performance.
- It has no "severity" level (everything looks the same).
- 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.
- Trace (0): Secrets, extremely detailed info.
- Debug (1): Internal variable states during development.
- Information (2): General flow ("User X logged in").
- Warning (3): Something unexpected but recoverable (Disk running low).
- Error (4): Operation failed (Database timeout).
- Critical (5): Application crash (Out of memory).
Implementation
[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:
{
"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
dotnet add package Serilog.AspNetCore
dotnet add package Serilog.Sinks.ConsoleStep 2: Configuration (Program.cs)
Serilog is unique because it should ideally start before the Host starts, to catch startup errors.
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.
{
"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
- Global Handling: Never use
try-catchfor generic server errors. UseIExceptionHandler. - Environment: Show details to developers, hide details from the public.
- ILogger: Use the abstraction. Avoid string interpolation in log messages.
- 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
Create a Global Exception Handler:
- Define a public class named
ProductionExceptionHandlerthat implements theIExceptionHandlerinterface. - The class should accept an
ILogger<ProductionExceptionHandler>through its constructor and store it in a private readonly field. - Implement the
TryHandleAsyncmethod.- Inside the method, log the exception at the
Errorlevel. Use the following structured logging template:"An unexpected error occurred: {Message}", passing the exception's message as the parameter. - Set the
HttpContext.Response.StatusCodeto500(Internal Server Error). - Write a standard
ProblemDetailsobject to the response body. This object must have the following properties:Status:500Type:"https://tools.ietf.org/html/rfc7231#section-6.6.1"Title:"An unexpected error occurred."
- The method must return a
ValueTask<bool>that evaluates totrue, indicating the exception has been successfully handled.
- Inside the method, log the exception at the
- Define a public class named
Configure
Program.cs:- In the service registration section, add the services required for your custom exception handler and for
ProblemDetailsto function correctly. - In the middleware pipeline configuration section, add logic to use the
DeveloperExceptionPageonly when the application is running in theDevelopmentenvironment. - For all other environments, configure the pipeline to use the global exception handler middleware.
- In the service registration section, add the services required for your custom exception handler and for
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
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
// Service Registrations
builder.Services.AddExceptionHandler<ProductionExceptionHandler>();
builder.Services.AddProblemDetails();
// Middleware Pipeline Configuration
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler();
}