Middleware Explained :👈 👉:Core Caching: In-Memory, Distributed Cache and Redis

ASP.NET Core Global Exception Handling and ProblemDetails

ASP.NET Core Global Exception Handling and ProblemDetails

1. Introduction

Global exception handling is an important part of building reliable ASP.NET Core applications. It provides a centralized mechanism to catch unhandled exceptions, log errors and return consistent error responses to clients.

Without centralized exception handling, developers may end up writing repetitive try-catch blocks in controllers, services and API endpoints.

ASP.NET Core provides built-in exception-handling middleware and the ProblemDetails standard to simplify error handling.

In this article, we will understand:

  • What global exception handling is and why it is required.
  • How ASP.NET Core handles unhandled exceptions.
  • What ProblemDetails is and why APIs use it.
  • How to implement centralized exception handling using IExceptionHandler.
  • How to map custom exceptions to appropriate HTTP status codes.
  • How to customize ProblemDetails responses.
  • How to handle validation errors and other HTTP error responses.
  • Best practices for production applications.

2. Table of Contents

  1. What Is Global Exception Handling?
  2. Why Do We Need Global Exception Handling?
  3. What Is ProblemDetails?
  4. ProblemDetails Properties
  5. Built-in Exception Handling in ASP.NET Core
  6. IExceptionHandler in ASP.NET Core
  7. Creating Custom Exceptions
  8. Mapping Exceptions to HTTP Status Codes
  9. Customizing ProblemDetails
  10. Handling HTTP Status Codes
  11. Handling Validation Errors
  12. Complete Controller-Based API Example
  13. Minimal API Example
  14. Exception Handling vs ProblemDetails
  15. Logging and Monitoring
  16. Best Practices
  17. Common Mistakes
  18. Interview Questions and Answers
  19. Summary

3. What Is Global Exception Handling?

Global exception handling is a centralized mechanism that catches unhandled exceptions occurring anywhere in the application's request-processing pipeline.

Instead of handling exceptions separately in every controller or endpoint, we configure one central exception handler.

Without Global Exception Handling

Developers may write repetitive try-catch blocks in individual controllers.

[HttpGet("{id}")]
public IActionResult GetUser(int id)
{
    try
    {
        var user = _userService.GetUser(id);
        return Ok(user);
    }
    catch (Exception ex)
    {
        return StatusCode(500, ex.Message);
    }
}

Problems:

  • Repeated try-catch blocks across controllers.
  • Inconsistent error response formats.
  • More difficult maintenance.
  • Risk of exposing internal exception messages.
  • Logging logic may be duplicated or forgotten.

With Global Exception Handling

We configure a centralized exception handler in the application pipeline.

builder.Services.AddProblemDetails();
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
var app = builder.Build();
app.UseExceptionHandler();
app.MapControllers();
app.Run();

Now, unhandled exceptions from downstream middleware, controllers and endpoints can be handled centrally.

Benefits:

  • Centralized exception handling.
  • Consistent API error responses.
  • Centralized logging.
  • Less repetitive code.
  • Better separation of concerns.
  • Safer error responses for production applications.

4. Why Do We Need Global Exception Handling?

Consider an e-commerce application with the following API endpoints:

  • GET /api/products
  • GET /api/products/10
  • POST /api/orders
  • GET /api/customers/20
  • POST /api/payments

Different operations can fail for different reasons.

Scenario Possible Exception or Error Expected HTTP Status
Product does not exist NotFoundException 404 Not Found
Invalid order data ValidationException 400 Bad Request
Duplicate order ConflictException 409 Conflict
Unauthenticated request Authentication failure 401 Unauthorized
Insufficient permissions Authorization failure 403 Forbidden
Unexpected database failure Database exception 500 Internal Server Error
External service unavailable Timeout or service exception Often 503 Service Unavailable or 504 Gateway Timeout, depending on the failure

A global exception handler allows us to map known application exceptions to appropriate HTTP status codes while handling unexpected exceptions safely.

5. What Is ProblemDetails?

ProblemDetails is a standardized JSON format for representing errors in HTTP APIs.

It is based on RFC 9457, which defines a common format for communicating HTTP API problems.

Instead of returning different error structures from different endpoints, an API can return a consistent response format.

Example ProblemDetails Response

{
    "type": "https://example.com/problems/user-not-found",
    "title": "User Not Found",
    "status": 404,
    "detail": "The requested user does not exist.",
    "instance": "/api/users/100",
    "traceId": "00-abcd1234..."
}

When a client receives this response, it can identify the error type, understand the HTTP status and display an appropriate message.

Why Use ProblemDetails?

  • Provides a consistent error response format.
  • Improves communication between APIs and clients.
  • Supports standard HTTP error information.
  • Allows additional application-specific properties.
  • Helps frontend applications handle errors consistently.
  • Reduces the need for custom error response structures.

6. ProblemDetails Properties

The standard ProblemDetails object defines five primary properties.

Property Description Example
type A URI identifying the type of problem. https://example.com/problems/not-found
title A short, human-readable summary of the problem type. User Not Found
status The HTTP status code associated with the problem. 404
detail A human-readable explanation of this particular occurrence. The requested user does not exist.
instance A URI identifying the specific occurrence of the problem. /api/users/100

Additional Extension Properties

ProblemDetails also supports extension properties for application-specific information.

For example:

{
    "type": "https://example.com/problems/not-found",
    "title": "User Not Found",
    "status": 404,
    "detail": "The requested user does not exist.",
    "instance": "/api/users/100",
    "traceId": "00-abcd1234...",
    "errorCode": "USER_NOT_FOUND"
}

Here, traceId and errorCode are extension properties, not standard members of the five-property ProblemDetails definition.

Important: Do not include passwords, access tokens, connection strings, database details or sensitive internal exception information in ProblemDetails responses.

7. Built-in Exception Handling in ASP.NET Core

ASP.NET Core provides built-in exception-handling middleware through UseExceptionHandler().

It catches unhandled exceptions from downstream middleware and allows the application to return an appropriate error response.

Basic Configuration

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddProblemDetails();
var app = builder.Build();
app.UseExceptionHandler();
app.UseStatusCodePages();
app.MapControllers();
app.Run();

In this configuration:

  • AddProblemDetails() registers the ProblemDetails service.
  • UseExceptionHandler() handles unhandled exceptions.
  • UseStatusCodePages() can generate response bodies for error status codes that do not already have a body.
  • MapControllers() maps controller endpoints.

Development and Production Environments

Development and production environments should handle errors differently.

Development:

  • Detailed exception information can be useful while debugging.
  • The Developer Exception Page can display diagnostic information.
  • Detailed errors should only be available in a properly protected development environment.

Production:

  • Return safe error messages.
  • Log detailed exception information internally.
  • Do not expose stack traces or internal implementation details.
  • Return consistent ProblemDetails responses where appropriate.

Example:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddProblemDetails();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseExceptionHandler();
    app.UseHsts();
}
app.UseHttpsRedirection();
app.MapControllers();
app.Run();

For a production API, you can also use a registered IExceptionHandler implementation, as explained below.

8. IExceptionHandler in ASP.NET Core

ASP.NET Core 8 introduced IExceptionHandler, an interface that allows developers to implement centralized exception-handling logic.

It provides a clean way to handle known application exceptions and generate consistent ProblemDetails responses.

IExceptionHandler Interface

public interface IExceptionHandler
{
    ValueTask<bool> TryHandleAsync(
        HttpContext httpContext,
        Exception exception,
        CancellationToken cancellationToken);
}

Understanding TryHandleAsync()

The method receives:

  • HttpContext: The current HTTP request and response context.
  • Exception: The exception that occurred.
  • CancellationToken: A token used to observe cancellation.

The method returns a Boolean value:

  • true: The exception has been handled. The handler must have written an appropriate response.
  • false: This handler did not handle the exception. ASP.NET Core can try another registered handler or use the configured fallback behavior.

Creating a Global Exception Handler

Create a class named GlobalExceptionHandler.cs.

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 occurred.");
        var problemDetails = new ProblemDetails
        {
            Status = StatusCodes.Status500InternalServerError,
            Title = "An unexpected error occurred.",
            Detail = "An error occurred while processing your request.",
            Instance = httpContext.Request.Path
        };
        problemDetails.Extensions["traceId"] =
            httpContext.TraceIdentifier;
        httpContext.Response.StatusCode =
            StatusCodes.Status500InternalServerError;
        await httpContext.Response.WriteAsJsonAsync(
            problemDetails,
            cancellationToken);
        return true;
    }
}

Register the Handler

Register the exception handler in Program.cs.

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddProblemDetails();
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
var app = builder.Build();
app.UseExceptionHandler();
app.UseHttpsRedirection();
app.MapControllers();
app.Run();

Now, unhandled exceptions are processed by the registered global exception handler.

Important IExceptionHandler Details

  • Register handlers using AddExceptionHandler<T>().
  • Register the exception-handling middleware using UseExceptionHandler().
  • Handlers are registered as singleton services.
  • Multiple handlers can be registered and are called in registration order.
  • A handler returning true stops further exception-handler processing.
  • A handler returning true must write the response itself, including its status code.
  • If no handler handles an exception, the configured fallback behavior is used.

Important lifetime consideration: Because IExceptionHandler implementations are singleton services, do not constructor-inject scoped services such as a normal scoped DbContext. If request-scoped work is required, use an appropriate scope or another request-aware design.

9. Creating Custom Exceptions

In real-world applications, different business scenarios require different exception types.

For example:

  • UserNotFoundException
  • ProductNotFoundException
  • ValidationException
  • DuplicateOrderException
  • InsufficientBalanceException

Creating meaningful exception types helps the global exception handler identify the problem and return the appropriate HTTP status code.

Example 1: NotFoundException

public class NotFoundException : Exception
{
    public NotFoundException(string message)
        : base(message)
    {
    }
}

Example 2: ConflictException

public class ConflictException : Exception
{
    public ConflictException(string message)
        : base(message)
    {
    }
}

Example 3: BusinessValidationException

public class BusinessValidationException : Exception
{
    public BusinessValidationException(string message)
        : base(message)
    {
    }
}

These exceptions can be thrown from application services when a business operation cannot be completed.

Example: Service Layer

public class UserService : IUserService
{
    public User GetUser(int id)
    {
        var user = FindUser(id);
        if (user == null)
        {
            throw new NotFoundException(
                $"User with ID {id} was not found.");
        }
        return user;
    }
    private User? FindUser(int id)
    {
        // Database lookup example
        return null;
    }
}

The service does not need to create an HTTP response. It communicates the application failure through an exception.

The global exception handler converts that exception into an HTTP response.

10. Mapping Exceptions to HTTP Status Codes

A useful global exception handler maps known application exceptions to appropriate HTTP status codes.

For example:

Exception HTTP Status Meaning
NotFoundException 404 Requested resource does not exist
BusinessValidationException 400 Request or business input is invalid
ConflictException 409 Request conflicts with the current resource state
UnauthorizedAccessException 403 in this example's mapping Access is forbidden
Unexpected Exception 500 Unexpected server-side failure

Note: Authentication failures should normally be handled by authentication middleware and return 401. Do not use a generic exception mapping as a replacement for proper authentication and authorization configuration. The example above maps UnauthorizedAccessException to 403 for an application-level forbidden condition.

Complete Exception Mapping Example

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 context,
        Exception exception,
        CancellationToken cancellationToken)
    {
        var (statusCode, title, detail) = exception switch
        {
            NotFoundException ex => (
                StatusCodes.Status404NotFound,
                "Resource Not Found",
                ex.Message),
            BusinessValidationException ex => (
                StatusCodes.Status400BadRequest,
                "Validation Error",
                ex.Message),
            ConflictException ex => (
                StatusCodes.Status409Conflict,
                "Resource Conflict",
                ex.Message),
            UnauthorizedAccessException => (
                StatusCodes.Status403Forbidden,
                "Forbidden",
                "You do not have permission to perform this operation."),
            _ => (
                StatusCodes.Status500InternalServerError,
                "Internal Server Error",
                "An unexpected error occurred.")
        };
        if (statusCode >= 500)
        {
            _logger.LogError(
                exception,
                "Unhandled server error.");
        }
        else
        {
            _logger.LogWarning(
                exception,
                "Request failed with status code {StatusCode}.",
                statusCode);
        }
        var problemDetails = new ProblemDetails
        {
            Status = statusCode,
            Title = title,
            Detail = detail,
            Instance = context.Request.Path
        };
        problemDetails.Extensions["traceId"] =
            context.TraceIdentifier;
        context.Response.StatusCode = statusCode;
        await context.Response.WriteAsJsonAsync(
            problemDetails,
            cancellationToken);
        return true;
    }
}

This implementation:

  1. Receives the unhandled exception.
  2. Identifies the exception type.
  3. Determines the appropriate HTTP status code.
  4. Creates a ProblemDetails response.
  5. Logs the exception appropriately.
  6. Returns the response to the client.

Security consideration: Only return exception messages when they are known to be safe for clients. For example, an application-defined NotFoundException may contain a safe message, but an arbitrary exception message should not be exposed. Unexpected exceptions should return a generic message.

11. Customizing ProblemDetails

ASP.NET Core allows developers to customize automatically generated ProblemDetails responses using ProblemDetailsOptions.

11.1 Using CustomizeProblemDetails

Register ProblemDetails and add common extension properties.

builder.Services.AddProblemDetails(options =>
{
    options.CustomizeProblemDetails = context =>
    {
        context.ProblemDetails.Extensions["traceId"] =
            context.HttpContext.TraceIdentifier;
        context.ProblemDetails.Extensions["application"] =
            "My ASP.NET Core API";
    };
});

Now, automatically generated ProblemDetails responses can include these additional properties.

Example Response

{
    "type": "about:blank",
    "title": "An error occurred.",
    "status": 500,
    "traceId": "00-abcd1234...",
    "application": "My ASP.NET Core API"
}

11.2 Using IProblemDetailsService

IProblemDetailsService is an abstraction used by ASP.NET Core to create and write ProblemDetails responses.

It can be injected into middleware or other components that need to produce standardized error responses.

Example:

public class CustomErrorMiddleware
{
    private readonly RequestDelegate _next;
    public CustomErrorMiddleware(RequestDelegate next)
    {
        _next = next;
    }
    public async Task InvokeAsync(
        HttpContext context,
        IProblemDetailsService problemDetailsService)
    {
        await _next(context);
        if (context.Response.StatusCode == 404
            && !context.Response.HasStarted
            && context.Response.ContentLength == null)
        {
            var problem = new ProblemDetails
            {
                Status = 404,
                Title = "Resource Not Found",
                Detail = "The requested endpoint does not exist."
            };
            await problemDetailsService.TryWriteAsync(
                new ProblemDetailsContext
                {
                    HttpContext = context,
                    ProblemDetails = problem
                });
        }
    }
}

This is a simplified example of using the ProblemDetails service for an empty 404 response. In a real application, ensure that the middleware is placed appropriately and does not overwrite an existing response.

11.3 Custom IProblemDetailsWriter

For advanced scenarios, you can implement IProblemDetailsWriter to control how ProblemDetails responses are written.

This is useful when an application needs custom content negotiation, serialization or response formatting.

For most applications, AddProblemDetails() with CustomizeProblemDetails is sufficient.

12. Handling HTTP Status Codes

Not all HTTP errors are caused by exceptions.

For example:

  • A requested endpoint may not exist and return 404.
  • A request may be forbidden and return 403.
  • A request may be invalid and return 400.
  • A resource may be unavailable and return 503.

These responses may be generated without throwing an exception.

UseStatusCodePages() can generate response bodies for certain error status codes when no response body has already been written.

Example

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails();
var app = builder.Build();
app.UseStatusCodePages();
app.MapGet("/test", () =>
{
    return Results.NotFound();
});
app.Run();

When the endpoint returns 404 without a response body, the Status Code Pages middleware can use the ProblemDetails service to generate a standardized error response.

Important: Status Code Pages does not replace exception handling. Use UseExceptionHandler() for unhandled exceptions and UseStatusCodePages() for eligible status-code responses that do not already contain a body.

13. Handling Validation Errors

Validation errors are client-side input problems and should normally return HTTP 400 Bad Request rather than HTTP 500 Internal Server Error.

ASP.NET Core supports ValidationProblemDetails, which extends ProblemDetails with an errors dictionary.

Example ValidationProblemDetails Response

{
    "type": "https://example.com/problems/validation",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "errors": {
        "Name": [
            "Name is required."
        ],
        "Email": [
            "Invalid email address."
        ]
    }
}

Using Data Annotations

public class CreateUserRequest
{
    [Required]
    public string Name { get; set; }
    [Required]
    [EmailAddress]
    public string Email { get; set; }
}

Controller Example

[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
    [HttpPost]
    public IActionResult CreateUser(CreateUserRequest request)
    {
        return Ok("User created successfully");
    }
}

With the [ApiController] attribute, invalid model state automatically produces an HTTP 400 response. ASP.NET Core uses a validation ProblemDetails response by default for this behavior.

For custom validation response formats, configure InvalidModelStateResponseFactory through ApiBehaviorOptions.

builder.Services.Configure<ApiBehaviorOptions>(options =>
{
    options.InvalidModelStateResponseFactory = context =>
    {
        var problemDetails = new ValidationProblemDetails(
            context.ModelState)
        {
            Status = StatusCodes.Status400BadRequest,
            Title = "Validation Failed",
            Detail = "Please correct the supplied input."
        };
        return new BadRequestObjectResult(problemDetails);
    };
});

This provides a consistent validation response across controller endpoints.

14. Complete Controller-Based API Example

Let's combine the concepts into a simple controller-based API.

Project Structure

MyApi
|
+-- Controllers
|   |
|   +-- UsersController.cs
|
+-- Exceptions
|   |
|   +-- NotFoundException.cs
|   +-- ConflictException.cs
|
+-- Middleware
|   |
|   +-- GlobalExceptionHandler.cs
|
+-- Services
|   |
|   +-- UserService.cs
|
+-- Program.cs

Step 1: Create NotFoundException

public class NotFoundException : Exception
{
    public NotFoundException(string message)
        : base(message)
    {
    }
}

Step 2: Create UserService

public class UserService
{
    public string GetUser(int id)
    {
        if (id <= 0)
        {
            throw new NotFoundException(
                "User was not found.");
        }
        if (id == 100)
        {
            throw new NotFoundException(
                "User with ID 100 was not found.");
        }
        return "John";
    }
}

Step 3: Create GlobalExceptionHandler

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 context,
        Exception exception,
        CancellationToken cancellationToken)
    {
        var (statusCode, title, detail) = exception switch
        {
            NotFoundException ex => (
                StatusCodes.Status404NotFound,
                "User Not Found",
                ex.Message),
            _ => (
                StatusCodes.Status500InternalServerError,
                "Internal Server Error",
                "An unexpected error occurred.")
        };
        if (statusCode == 500)
        {
            _logger.LogError(
                exception,
                "Unexpected error occurred.");
        }
        else
        {
            _logger.LogWarning(
                exception,
                "Resource was not found.");
        }
        var problemDetails = new ProblemDetails
        {
            Status = statusCode,
            Title = title,
            Detail = detail,
            Instance = context.Request.Path
        };
        problemDetails.Extensions["traceId"] =
            context.TraceIdentifier;
        context.Response.StatusCode = statusCode;
        await context.Response.WriteAsJsonAsync(
            problemDetails,
            cancellationToken);
        return true;
    }
}

Step 4: Create UsersController

[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
    private readonly UserService _userService;
    public UsersController(UserService userService)
    {
        _userService = userService;
    }
    [HttpGet("{id}")]
    public IActionResult GetUser(int id)
    {
        var user = _userService.GetUser(id);
        return Ok(new
        {
            Id = id,
            Name = user
        });
    }
}

Step 5: Configure Program.cs

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddScoped<UserService>();
builder.Services.AddProblemDetails();
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler();
    app.UseHsts();
}
else
{
    app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.MapControllers();
app.Run();

Testing the API

Request 1:

GET /api/users/1

Response: HTTP 200 OK

{
    "id": 1,
    "name": "John"
}

Request 2:

GET /api/users/100

Response: HTTP 404 Not Found

{
    "title": "User Not Found",
    "status": 404,
    "detail": "User with ID 100 was not found.",
    "instance": "/api/users/100",
    "traceId": "00-abcd1234..."
}

Request 3:

If an unexpected exception occurs, the handler returns HTTP 500 with a generic message rather than exposing internal exception details.

15. Minimal API Example

Global exception handling and ProblemDetails also work with Minimal APIs.

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails();
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
var app = builder.Build();
app.UseExceptionHandler();
app.UseStatusCodePages();
app.MapGet("/users/{id:int}", (int id) =>
{
    if (id == 100)
    {
        throw new NotFoundException(
            "User was not found.");
    }
    return Results.Ok(new
    {
        Id = id,
        Name = "John"
    });
});
app.Run();

The same global exception handler can be reused by controller-based APIs and Minimal APIs.

16. Exception Handling vs ProblemDetails

These two concepts are related, but they serve different purposes.

Aspect Exception Handling ProblemDetails
Purpose Catches and processes exceptions Provides a standardized error response format
Responsibility Error detection, handling and logging Error representation
ASP.NET Core API UseExceptionHandler and IExceptionHandler AddProblemDetails and ProblemDetails
Output Depends on configured handler Structured error response
Can work independently? Yes Yes

Simple explanation:

  • Exception handling decides what to do when an exception occurs.
  • ProblemDetails defines how the error information is represented in the HTTP response.

They work together to create a centralized and consistent API error-handling strategy.

17. Logging and Monitoring

Returning an error response to the client is only one part of exception handling. Production applications must also record enough information to investigate failures.

What Should Be Logged?

  • Exception type.
  • Exception details and stack trace in internal logs.
  • Request path and HTTP method.
  • HTTP status code.
  • Trace identifier or correlation identifier.
  • Relevant application context that is safe to record.

Structured Logging Example

_logger.LogError(
    exception,
    "Request failed. Path: {Path}, TraceId: {TraceId}",
    context.Request.Path,
    context.TraceIdentifier);

Why Is TraceId Important?

Suppose a frontend application receives this response:

{
    "title": "Internal Server Error",
    "status": 500,
    "traceId": "00-123456789abcdef..."
}

The support or development team can use the trace identifier to correlate the client error with server-side logs and distributed tracing data.

In microservices, trace context can help connect activity across multiple services involved in a single request.

18. Best Practices

1. Use Centralized Exception Handling

Prefer UseExceptionHandler() and IExceptionHandler instead of repeating try-catch blocks in every controller.

2. Use Appropriate HTTP Status Codes

Map known application failures to meaningful HTTP status codes.

  • 400 for invalid requests.
  • 401 for unauthenticated requests.
  • 403 for forbidden requests.
  • 404 for missing resources.
  • 409 for resource conflicts.
  • 500 for unexpected server failures.
  • 503 for temporary service unavailability where appropriate.

3. Never Expose Internal Exception Details

Do not return stack traces, database errors, internal file paths, connection strings or sensitive implementation information to clients.

4. Use ProblemDetails Consistently

Use the standard ProblemDetails format for API errors instead of creating unrelated JSON structures for every endpoint.

5. Log Unexpected Exceptions

Record unexpected exceptions internally with enough information to investigate the issue.

6. Avoid Duplicate Logging

Decide which component is responsible for logging handled exceptions. Avoid logging the same exception repeatedly in middleware, handlers and controllers.

In .NET 10, exception-handling middleware suppresses its default diagnostics for exceptions handled by an IExceptionHandler returning true, unless configured otherwise. Earlier versions have different diagnostic behavior.

7. Do Not Use Exceptions for Normal Business Flow

Exceptions should represent exceptional situations, not routine control flow. For expected outcomes such as a normal search returning no results, use an appropriate result or response rather than throwing an exception.

8. Keep Exception Types Meaningful

Create application-specific exceptions only when they represent useful and distinct failure conditions.

9. Handle Validation Separately

Use model validation and ValidationProblemDetails for invalid client input instead of treating every validation failure as an internal server error.

10. Test Error Responses

Test both expected application exceptions and unexpected failures. Verify status codes, response bodies and logging behavior.

19. Common Mistakes

Mistake 1: Returning Exception Messages Directly

return Results.Problem(
    detail: exception.Message);

Problem: An unexpected exception message may contain internal implementation details.

Solution: Return a generic message for unexpected exceptions and log the actual exception internally.

Mistake 2: Registering IExceptionHandler Without UseExceptionHandler()

Problem: Registering an exception handler alone does not activate it.

Solution: Configure both:

builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
app.UseExceptionHandler();

Mistake 3: Returning true Without Writing a Response

Problem: A handler claims that the exception is handled, but no valid response is written.

Solution: Set the status code and write the response before returning true.

Mistake 4: Treating Every Exception as HTTP 500

Problem: Known conditions such as missing resources and business conflicts are incorrectly returned as server errors.

Solution: Map known application exceptions to appropriate status codes.

Mistake 5: Confusing Exceptions with HTTP Error Status Codes

Problem: A 404 response does not necessarily mean an exception was thrown.

Solution: Use exception handling for exceptions and Status Code Pages for eligible status-code responses without a body.

Mistake 6: Injecting Scoped Dependencies into a Singleton Exception Handler

Problem: IExceptionHandler is registered as a singleton. Direct constructor injection of scoped services can cause dependency lifetime problems.

Solution: Avoid scoped constructor dependencies or use an appropriate scope when request-scoped work is genuinely required.

20. Interview Questions and Answers

1. What is global exception handling in ASP.NET Core?

It is a centralized mechanism that catches unhandled exceptions from the request pipeline and generates appropriate error responses.

2. Why do we need global exception handling?

It avoids repetitive try-catch blocks, provides consistent error responses, centralizes logging and makes applications easier to maintain.

3. What is ProblemDetails?

ProblemDetails is a standardized HTTP API error response format defined by RFC 9457. It provides properties such as type, title, status, detail and instance.

4. What is IExceptionHandler?

IExceptionHandler is an ASP.NET Core interface used to implement centralized exception-handling logic. It provides the TryHandleAsync() method.

5. Which ASP.NET Core version introduced IExceptionHandler?

IExceptionHandler was introduced in ASP.NET Core 8.

6. What is the purpose of AddProblemDetails()?

It registers the default ProblemDetails service, which helps ASP.NET Core generate standardized error responses.

7. What is the purpose of UseExceptionHandler()?

It adds exception-handling middleware to the HTTP request pipeline so unhandled exceptions can be processed centrally.

8. What is the difference between UseExceptionHandler() and UseStatusCodePages()?

UseExceptionHandler() handles unhandled exceptions. UseStatusCodePages() can generate response bodies for eligible error status codes that do not already have a body.

9. What is ValidationProblemDetails?

It is a specialized ProblemDetails response that includes an errors dictionary for reporting validation failures.

10. Can we create custom exceptions?

Yes. We can create custom exception classes such as NotFoundException, ConflictException and BusinessValidationException to represent specific application failures.

11. What happens when TryHandleAsync() returns true?

The exception is considered handled, and further registered exception handlers are not called. The handler must have written a complete response.

12. What happens when TryHandleAsync() returns false?

The exception handler middleware can try the next registered handler. If none handles the exception, the configured fallback behavior is used.

13. Why should we not expose exception messages in production?

Exception messages can reveal sensitive implementation details such as database information, internal paths and application structure.

14. What is the purpose of traceId in ProblemDetails?

It helps correlate a client-facing error response with server-side logs and tracing information.

15. What is the difference between 401 and 403?

401 indicates that valid authentication credentials are missing or invalid. 403 indicates that the request is understood, but access is forbidden.

16. Can ProblemDetails be customized?

Yes. It can be customized using ProblemDetailsOptions.CustomizeProblemDetails, a custom IProblemDetailsWriter or the IProblemDetailsService.

17. Should every business error be represented by an exception?

No. Exceptions should be reserved for exceptional situations. Expected outcomes can be represented using result objects or normal HTTP responses.

18. Is global exception handling a replacement for validation?

No. Validation should be performed separately. Validation errors should normally return HTTP 400 with a ValidationProblemDetails response.

21. Summary

Concept Purpose
Global Exception Handling Centralized handling of unhandled exceptions
UseExceptionHandler() Adds exception-handling middleware
IExceptionHandler Custom centralized exception handler
AddExceptionHandler() Registers an IExceptionHandler implementation
ProblemDetails Standard HTTP API error response format
AddProblemDetails() Registers the ProblemDetails service
ValidationProblemDetails Represents validation errors
IProblemDetailsService Creates and writes ProblemDetails responses
UseStatusCodePages() Generates response bodies for eligible error status codes
TraceId Helps correlate client errors with server-side diagnostics

22. Conclusion

Global exception handling and ProblemDetails are important features for building reliable ASP.NET Core APIs.

Global exception handling provides a centralized way to catch and process unhandled exceptions, while ProblemDetails provides a consistent format for communicating errors to API clients.

For modern ASP.NET Core applications, a useful approach is to combine IExceptionHandler, UseExceptionHandler(), AddProblemDetails() and UseStatusCodePages() where appropriate.

This approach improves maintainability, consistency, security and troubleshooting across the application.

🔙
Middleware Explained :👈 👉:Core Caching: In-Memory, Distributed Cache and Redis