Claude
Skills
Sign in
Back

exception-handling

Included with Lifetime
$97 forever

Comprehensive exception handling patterns for ASP.NET Core Razor Pages applications. Covers global exception handling, ProblemDetails API, custom error pages, exception middleware, and graceful degradation strategies. Use when implementing error handling in Razor Pages applications, configuring global exception middleware, or creating user-friendly error pages and API error responses.

Backend & APIs

What this skill does


You are a senior ASP.NET Core architect specializing in exception handling. When implementing error handling in Razor Pages applications, apply these patterns to ensure graceful failures, proper logging, and excellent user experience. Target .NET 8+ with nullable reference types enabled.

## Rationale

Proper exception handling is critical for production applications. Poor handling leads to unhandled exceptions, information leakage, poor user experience, and security vulnerabilities. These patterns provide a layered approach to exception handling that ensures all errors are caught, logged, and handled appropriately.

## Exception Handling Layers

| Layer | Purpose | Scope |
|-------|---------|-------|
| **Global Middleware** | Catch-all unhandled exceptions | Application-wide |
| **Exception Filter** | Handle controller/page-specific exceptions | PageModel |
| **Try-Catch Blocks** | Handle specific operations | Method level |
| **Error Pages** | Display user-friendly errors | UI |

## Pattern 1: Global Exception Handler Configuration

### Program.cs Setup

```csharp
var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

// Configure exception handling middleware (order matters!)
if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage(); // Detailed errors for dev
}
else
{
    app.UseExceptionHandler("/Error"); // Production error page
    app.UseStatusCodePagesWithReExecute("/NotFound", "?statusCode={0}");
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

app.MapRazorPages();
```

### Error Page Model

```csharp
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
[IgnoreAntiforgeryToken]
public class ErrorModel(ILogger<ErrorModel> logger, IWebHostEnvironment env) : PageModel
{
    public string? RequestId { get; set; }
    public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
    public string? ErrorMessage { get; set; }
    public string? StackTrace { get; set; }
    public int StatusCode { get; set; } = 500;

    public void OnGet(int? statusCode = null)
    {
        RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
        StatusCode = statusCode ?? 500;

        var exceptionHandlerPathFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
        
        if (exceptionHandlerPathFeature?.Error != null)
        {
            var ex = exceptionHandlerPathFeature.Error;
            var path = exceptionHandlerPathFeature.Path;
            
            logger.LogError(ex, 
                "Unhandled exception at {Path}. RequestId: {RequestId}", 
                path, RequestId);

            // Only expose details in development
            if (env.IsDevelopment())
            {
                ErrorMessage = ex.Message;
                StackTrace = ex.StackTrace;
            }
            else
            {
                ErrorMessage = "An unexpected error occurred. Please try again later.";
            }
        }
    }
}
```

### Error.cshtml

```csharp
@page
@model ErrorModel
@{
    ViewData["Title"] = "Error";
}

<h1 class="text-danger">Error</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>

@if (Model.ShowRequestId)
{
    <p>
        <strong>Request ID:</strong> <code>@Model.RequestId</code>
    </p>
    <p class="text-muted">
        Please include this ID when contacting support.
    </p>
}

@if (!string.IsNullOrEmpty(Model.ErrorMessage))
{
    <h3>Error Details</h3>
    <p>@Model.ErrorMessage</p>
    
    @if (!string.IsNullOrEmpty(Model.StackTrace))
    {
        <pre class="alert alert-secondary">@Model.StackTrace</pre>
    }
}
```

## Pattern 2: Status Code Pages

### NotFound Page Model

```csharp
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public class NotFoundModel : PageModel
{
    public int StatusCode { get; set; }
    public string? OriginalPath { get; set; }

    public void OnGet(int statusCode)
    {
        StatusCode = statusCode;
        OriginalPath = HttpContext.Features.Get<IStatusCodeReExecuteFeature>()?.OriginalPath;
    }
}
```

### NotFound.cshtml

```csharp
@page
@model NotFoundModel
@{
    ViewData["Title"] = "Not Found";
}

<div class="text-center">
    <h1 class="display-1">@Model.StatusCode</h1>
    <h2>Page Not Found</h2>
    
    @if (!string.IsNullOrEmpty(Model.OriginalPath))
    {
        <p>The page <code>@Model.OriginalPath</code> could not be found.</p>
    }
    
    <a asp-page="/Index" class="btn btn-primary">Return to Home</a>
</div>
```

## Pattern 3: Custom Exception Middleware

For more control than the built-in exception handler, create custom middleware.

```csharp
public class GlobalExceptionHandlingMiddleware(RequestDelegate next, ILogger<GlobalExceptionHandlingMiddleware> logger)
{
    public async Task Invoke(HttpContext context)
    {
        try
        {
            await next(context);
        }
        catch (Exception ex)
        {
            await HandleExceptionAsync(context, ex);
        }
    }

    private async Task HandleExceptionAsync(HttpContext context, Exception exception)
    {
        logger.LogError(exception, "Unhandled exception occurred");

        context.Response.ContentType = "application/json";
        
        var response = exception switch
        {
            ValidationException ex => CreateValidationErrorResponse(context, ex),
            NotFoundException ex => CreateNotFoundResponse(context, ex),
            UnauthorizedAccessException ex => CreateUnauthorizedResponse(context, ex),
            ConflictException ex => CreateConflictResponse(context, ex),
            _ => CreateGenericErrorResponse(context, exception)
        };

        context.Response.StatusCode = response.Status ?? 500;
        await context.Response.WriteAsJsonAsync(response);
    }

    private static ProblemDetails CreateValidationErrorResponse(HttpContext context, ValidationException ex)
    {
        return new ValidationProblemDetails(ex.Errors)
        {
            Status = StatusCodes.Status400BadRequest,
            Type = "https://tools.ietf.org/html/rfc7231#section-6.5.1",
            Title = "Validation Failed",
            Detail = "One or more validation errors occurred",
            Instance = context.Request.Path
        };
    }

    private static ProblemDetails CreateNotFoundResponse(HttpContext context, NotFoundException ex)
    {
        return new ProblemDetails
        {
            Status = StatusCodes.Status404NotFound,
            Type = "https://tools.ietf.org/html/rfc7231#section-6.5.4",
            Title = "Not Found",
            Detail = ex.Message,
            Instance = context.Request.Path
        };
    }

    private static ProblemDetails CreateUnauthorizedResponse(HttpContext context, UnauthorizedAccessException ex)
    {
        return new ProblemDetails
        {
            Status = StatusCodes.Status403Forbidden,
            Type = "https://tools.ietf.org/html/rfc7231#section-6.5.3",
            Title = "Forbidden",
            Detail = "You do not have permission to perform this action",
            Instance = context.Request.Path
        };
    }

    private static ProblemDetails CreateConflictResponse(HttpContext context, ConflictException ex)
    {
        return new ProblemDetails
        {
            Status = StatusCodes.Status409Conflict,
            Type = "https://tools.ietf.org/html/rfc7231#section-6.5.8",
            Title = "Conflict",
            Detail = ex.Message,
            Instance = context.Request.Path
        };
    }

    private static ProblemDetails CreateGenericErrorResponse(HttpContext context, Exception ex)
    {
        return new ProblemDetails
        {
            Status = StatusCodes.Status500InternalServerError,
            Type = "https://tools.ietf.org/html/rfc7231#section-6.6.1",
            Title = "Internal Server Error",
            Detail = "An unexpected error occurred",
            Instance = con

Related in Backend & APIs