exception-handling
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.
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 = conRelated in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.