LESSON 8 OF 12

8. Exception Logging and Global Error Handling

Build safe, traceable, and structured global error handling with ProblemDetails while separating expected business-rule failures from unexpected application exceptions.

50 dk 88

Introduction

Error handling in an ASP.NET Core application is not simply a matter of returning 500 Internal Server Error. In production, the application must record the failure at the right severity, preserve request context, provide enough diagnostic information for engineers, and return a safe response to the client. In this lesson, we connect the Serilog, structured logging, request logging, correlation ID, and trace ID concepts from the previous lessons with centralized exception handling.

Instead of repeating try/catch blocks in every endpoint, we will create one global middleware. The middleware records unexpected exceptions with LogError and the exception object, while expected business-rule failures are logged at an appropriate level without producing unnecessary stack-trace noise. The HTTP response uses the ProblemDetails format, but stack traces and internal implementation details are never exposed to the client.

Core principle: server logs should be detailed for diagnosis, while client responses should be safe and stable.

1. Separating expected and unexpected failures

Not every exception means that the application is broken. For example, an order may be rejected because the requested quantity exceeds available inventory. This is an expected business result and can normally be returned as 400, 404, or 409.

In contrast, a lost database connection, a null reference, or an unexpected external-service failure means that the operation could not be completed because of a technical problem. These failures should normally be logged at Error level with the exception preserved.

Failure typeExampleLog levelClient response
Expected business ruleInsufficient stockWarning or Information409 Conflict
Invalid client inputMissing or invalid fieldInformation or Warning400 Bad Request
Missing resourceOrder does not existInformation404 Not Found
Unexpected application failureDatabase exceptionError500 Internal Server Error

When LogError(exception, message, ...) receives the exception as its first argument, Serilog can preserve the exception type, stack trace, and inner exception as structured event data. Logging only exception.Message loses a significant part of the diagnostic context.

2. The ProblemDetails contract

ASP.NET Core supports the ProblemDetails approach for standardizing API errors. A response commonly contains type, title, status, detail, and instance. Application-specific information, such as errorCode or traceId, can be added as extension members.

Do not return a stack trace, SQL text, file path, connection string, or internal service name to the client. Such information can create a security risk and makes the client dependent on server implementation details. A stable error code, a safe title, and a trace identifier are usually sufficient for client-side behavior and support diagnostics.

3. Defining a business-rule exception

A dedicated exception type makes business-rule failures explicit. It carries the error code and HTTP status code that the middleware needs to select the response.

public sealed class BusinessRuleException : Exception
{
    public BusinessRuleException(
        string code,
        string message,
        int statusCode = StatusCodes.Status409Conflict)
        : base(message)
    {
        Code = code;
        StatusCode = statusCode;
    }

    public string Code { get; }
    public int StatusCode { get; }
}

An order service can use it when inventory is insufficient:

if (product.Stock < request.Quantity)
{
    throw new BusinessRuleException(
        "ORDER_STOCK_INSUFFICIENT",
        "The requested quantity is not available.");
}

The client may use the code to select a localized message. Even so, directly exposing arbitrary exception messages is less controlled than mapping known codes to safe public messages in the global handler.

4. Creating the global exception middleware

The middleware catches exceptions thrown by later pipeline components. If the response has not started, it sets the status code and writes a ProblemDetails response. If the response has already started, a safe error body can no longer be written, so the exception is rethrown and can be handled by the hosting infrastructure.

using Microsoft.AspNetCore.Diagnostics;

public sealed class GlobalExceptionMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<GlobalExceptionMiddleware> _logger;
    private readonly IProblemDetailsService _problemDetails;

    public GlobalExceptionMiddleware(
        RequestDelegate next,
        ILogger<GlobalExceptionMiddleware> logger,
        IProblemDetailsService problemDetails)
    {
        _next = next;
        _logger = logger;
        _problemDetails = problemDetails;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception exception)
        {
            await HandleExceptionAsync(context, exception);
        }
    }

    private async Task HandleExceptionAsync(
        HttpContext context,
        Exception exception)
    {
        if (context.Response.HasStarted)
        {
            _logger.LogError(
                exception,
                "The response had already started while handling an exception. Path: {Path}",
                context.Request.Path);

            throw exception;
        }

        var isBusinessRule = exception is BusinessRuleException businessRule;
        var statusCode = isBusinessRule
            ? businessRule!.StatusCode
            : StatusCodes.Status500InternalServerError;
        var errorCode = isBusinessRule
            ? businessRule!.Code
            : "UNEXPECTED_ERROR";

        using (_logger.BeginScope(new Dictionary<string, object>
        {
            ["ErrorCode"] = errorCode,
            ["RequestPath"] = context.Request.Path.ToString(),
            ["TraceId"] = context.TraceIdentifier
        }))
        {
            if (isBusinessRule)
            {
                _logger.LogWarning(
                    "Business rule rejected the request. ErrorCode: {ErrorCode}, StatusCode: {StatusCode}",
                    errorCode,
                    statusCode);
            }
            else
            {
                _logger.LogError(
                    exception,
                    "Unexpected exception while processing the request. ErrorCode: {ErrorCode}",
                    errorCode);
            }
        }

        context.Response.StatusCode = statusCode;

        await _problemDetails.WriteAsync(new ProblemDetailsContext
        {
            HttpContext = context,
            ProblemDetails =
            {
                Status = statusCode,
                Title = isBusinessRule
                    ? "The request could not be completed."
                    : "An unexpected error occurred.",
                Type = $"https://api.example.com/problems/{errorCode.ToLowerInvariant()}",
                Detail = isBusinessRule
                    ? businessRule!.Message
                    : "The server could not complete the request.",
                Instance = context.Request.Path,
                Extensions =
                {
                    ["errorCode"] = errorCode,
                    ["traceId"] = context.TraceIdentifier
                }
            }
        });
    }
}

The api.example.com address is only an example problem type URI. In a real project, use your own documentation domain or define a stable URI contract. The URI does not necessarily need to render a web page; its primary purpose is to identify the problem type consistently.

5. Configuring Program.cs

Register the ProblemDetails service and add the middleware before the endpoints. Do not combine a custom global middleware and UseExceptionHandler in a way that causes the same exception to be logged twice. Select one component as the owner of the global response and logging policy.

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddProblemDetails();

var app = builder.Build();

app.UseMiddleware<GlobalExceptionMiddleware>();
app.UseHttpsRedirection();
app.MapControllers();

app.Run();

The Serilog configuration from the previous lessons converts ILogger<GlobalExceptionMiddleware> calls into Serilog events. If the correlation ID middleware runs before the exception middleware, its scope or log context can also be included in the error event. For distributed systems, prefer the existing tracing context for the trace ID; HttpContext.TraceIdentifier can serve as an additional identifier for the HTTP request.

6. Separating safe logs from safe responses

Server logs may contain exception details for diagnosis, but personal data, access tokens, passwords, card numbers, and sensitive request bodies must be masked or excluded. Destructuring an entire request object into a log event can unintentionally expose secrets.

  • Logs may contain: exception type, stack trace, error code, endpoint, HTTP method, trace ID, and safe user or tenant identifiers.
  • Client responses may contain: status code, stable error code, safe title, general detail, and trace ID.
  • They should not contain: stack traces, inner exception messages, SQL statements, connection strings, server file paths, or secret values.

For expected business-rule failures, omitting the exception object from the LogWarning call is often cleaner because the event represents a rejected business operation rather than an application outage. If audit requirements exist, record structured fields such as actor, resource, rule code, and outcome separately.

7. Testing the error pipeline

Testing only successful requests is not enough. At minimum, verify the following cases:

  1. A BusinessRuleException produces HTTP 409.
  2. The ProblemDetails body contains errorCode and traceId.
  3. An unexpected InvalidOperationException produces HTTP 500.
  4. The 500 response does not contain a stack trace or exception message.
  5. Each scenario creates the expected log level and structured properties.
  6. An exception after the response has started is not silently swallowed.

ASP.NET Core integration tests can use WebApplicationFactory<Program> and HttpClient to execute the real HTTP pipeline:

[Fact]
public async Task Unexpected_error_returns_safe_problem_details()
{
    using var factory = new WebApplicationFactory<Program>();
    using var client = factory.CreateClient();

    var response = await client.GetAsync("/api/test/unexpected-error");
    var body = await response.Content.ReadAsStringAsync();

    Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
    Assert.Contains("UNEXPECTED_ERROR", body);
    Assert.DoesNotContain("System.InvalidOperationException", body);
}

For log assertions, use an in-memory sink or a dedicated ILoggerProvider in the test environment. Avoid making tests depend on the exact rendered text; validate the level, event name, exception presence, and critical structured properties instead.

8. Common mistakes

  • Adding try/catch to every controller action: This creates duplication and inconsistent responses. Use centralized middleware or IExceptionHandler for cross-cutting behavior.
  • Returning exception messages to clients: Internal system details may be exposed. Return a safe public message.
  • Losing the stack trace: throw ex; can damage the original stack trace. Use throw; when rethrowing.
  • Logging every business rule at Error: Warning noise can hide real application failures.
  • Using two global handlers: The same exception may be logged twice, or response headers may already be committed.
  • Failing to propagate trace context: It becomes difficult to connect a client-visible error with its server log.
  • Destructuring sensitive objects: Request objects and exception data should not be logged without a data-classification review.

Practice exercise

Add an /api/orders/{id}/cancel endpoint. Return 404 with code ORDER_NOT_FOUND when the order does not exist, and 409 with code ORDER_ALREADY_CANCELLED when it has already been cancelled. Use BusinessRuleException for both cases. Then make the simulated database call fail and observe the 500 response for an unexpected exception. Inspect the events in Seq or the file sink and compare the log level, trace ID, request path, and error code for every scenario.

Conclusion

Global exception handling standardizes error behavior in one place. ProblemDetails defines a predictable client contract, while Serilog and ILogger produce structured events that are useful for server-side diagnosis. Separating expected business-rule failures from unexpected technical failures is essential for choosing correct log levels, reducing alert noise, and finding real problems faster.

In the next lesson, we will connect these logs with OpenTelemetry tracing and metrics so that we can follow not only one request, but an entire flow across multiple services.

Sources