Skip to main content

Lesson 3 of 8

Global Exception Handling & ProblemDetails

Unhandled exceptions in ASP.NET Core controllers return 500 with a generic response - or worse, stack traces to clients. UseExceptionHandler middleware catches all unhandled exceptions and converts them to RFC 7807 ProblemDetails responses with appropriate HTTP status codes.

30 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Global Exception Handler Middleware

Global Exception Handler Middleware
using Microsoft.AspNetCore.Diagnostics;

// ━━ Method 1: IExceptionHandler (.NET 8) - preferred, DI-friendly ━━
public class GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger) : IExceptionHandler
{
    public async ValueTask<bool> TryHandleAsync(
        HttpContext context,
        Exception exception,
        CancellationToken ct)
    {
        // Log with full exception details
        logger.LogError(exception,
            "Unhandled exception for {Method} {Path}",
            context.Request.Method, context.Request.Path);

        // Map exception type to HTTP status + ProblemDetails
        var (statusCode, title) = exception switch
        {
            NotFoundException         => (404, "Resource Not Found"),
            ValidationException       => (422, "Validation Failed"),
            ConflictException         => (409, "Conflict"),
            UnauthorizedException     => (401, "Unauthorized"),
            ForbiddenException        => (403, "Forbidden"),
            TimeoutException          => (504, "Gateway Timeout"),
            _                         => (500, "Internal Server Error")
        };

        var problem = new ProblemDetails
        {
            Status = statusCode,
            Title = title,
            Detail = exception.Message,
            Instance = context.Request.Path,
            Type = $"https://errors.myapp.com/{statusCode}"
        };

        // Add correlation ID for tracing
        if (context.Items.TryGetValue("CorrelationId", out var correlationId))
            problem.Extensions["correlationId"] = correlationId;

        // In development, include stack trace
        if (context.RequestServices
            .GetRequiredService<IHostEnvironment>().IsDevelopment())
            problem.Extensions["stackTrace"] = exception.StackTrace;

        context.Response.StatusCode = statusCode;
        await context.Response.WriteAsJsonAsync(problem, ct);

        return true; // handled - don't rethrow
    }
}

// ━━ Registration ━━
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
builder.Services.AddProblemDetails();

// In middleware pipeline (FIRST position - catches all downstream exceptions):
app.UseExceptionHandler();

// ━━ Custom domain exceptions ━━
public abstract class DomainException(string message) : Exception(message);
public class NotFoundException(string resource, object id)
    : DomainException($"{resource} with id '{id}' was not found");
public class ValidationException(string message) : DomainException(message);
public class ConflictException(string message) : DomainException(message);
public class UnauthorizedException(string message) : DomainException(message);
public class ForbiddenException(string message) : DomainException(message);

// ━━ Usage in service - throw, don't return error codes ━━
// (Result<T> pattern from M1 for EXPECTED business errors)
// (exceptions for UNEXPECTED errors and domain invariant violations)
public async Task<Product> GetProductAsync(string id, CancellationToken ct)
{
    var product = await repository.FindByIdAsync(id, ct);
    if (product is null)
        throw new NotFoundException(nameof(Product), id); // → 404 ProblemDetails automatically

    return product;
}

// Placeholder types
interface IHostEnvironment { bool IsDevelopment(); }
record Product(string Id);
interface IRepository { Task<Product?> FindByIdAsync(string id, CancellationToken ct); }
IRepository repository = null!;

Tip

Tip

Practice Global Exception Handling ProblemDetails in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

.NET provides a unified platform for building various application types

Practice Task

Note

Practice Task - (1) Write a working example of Global Exception Handling ProblemDetails from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Global Exception Handling ProblemDetails is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.

Topics in This Module

0/8 done