Token导航 LogoToken导航

Agent Skill · 开发

exception-handling(异常处理)

exception-handling 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

exception-handling 是开发类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为需要联网;许可证信息还不明确,第三方扫描有未通过项,按安装量在开发类的 21,746 个 Skill 里排第 18,928。

总安装 306周安装 13GitHub Stars 15下载 107核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:exception-handling(异常处理)
来源仓库:https://github.com/wshaddix/dotnet-skills
仓库路径:skills/exception-handling
安装命令:
npx skills add https://github.com/wshaddix/dotnet-skills --skill exception-handling
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/wshaddix/dotnet-skills --skill exception-handling

这个 Skill 是做什么的

开发类 Skill 面向写代码、改代码和排查问题,一般会读写仓库文件,部分还会执行构建或测试命令。

针对 ASP.NET Core Razor Pages 的异常处理指导。提供分层错误捕获、日志记录与用户体验优化策略。适用于 .NET 8+ 项目并启用可为空引用类型。推荐使用中间件与页面模型分离错误处理逻辑。exception-handling 属于开发类 Skill,可作为该场景下的辅助能力补充。

禁止在非边界层捕获基类 Exception 异常。

来源仓库内路径:skills/exception-handling

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/wshaddix/dotnet-skills --skill exception-handl…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要需要联网,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

exception-handling 怎么安装?

在终端执行 npx skills add https://github.com/wshaddix/dotnet-skills --skill exception-handling。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

exception-handling 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

exception-handling 需要什么权限?

权限级别是需要联网。该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

exception-handling 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

exception-handling 用的人多吗?

公开数据是累计安装 306 次,近一周安装 13 次,下载 107 次,GitHub 15 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

exception-handling 安全吗?

第三方扫描有未通过项,风险较高。除非你确认过源码,否则不建议直接安装到常用环境。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。

先想清楚的地方

  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方扫描存在提醒项或未通过项,需要人工逐条确认。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理开发类任务、又不想每次都手写提示词的人。

不太适合

  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

开发类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
skill-vetter

技能审查员 · OpenClaw

8,779,018986操作浏览器MIT-0通过
ontology

本体论 · OpenClaw

6,636,960576只读MIT-0通过
entra-app-registration

内部应用程序注册 · Codex、Claude

6,631,872764接触敏感数据未明确通过
entra-app-registration

内部应用程序注册 · Codex、Claude

3,757,680201接触敏感数据未明确通过
nano-banana-pro

纳米香蕉专业版 · OpenClaw

3,526,898364接触敏感数据MIT-0有提醒
exception-handling

异常处理 · 本页

30615需要联网未明确未通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

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

LayerPurposeScope
Global MiddlewareCatch-all unhandled exceptionsApplication-wide
Exception FilterHandle controller/page-specific exceptionsPageModel
Try-Catch BlocksHandle specific operationsMethod level
Error PagesDisplay user-friendly errorsUI

Pattern 1: Global Exception Handler Configuration

Program.cs Setup

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

[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

@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

[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

@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.

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 = context.Request.Path
        };
    }
}

// Extension method
public static class ExceptionHandlingExtensions
{
    public static IApplicationBuilder UseGlobalExceptionHandling(this IApplicationBuilder app)
    {
        return app.UseMiddleware<GlobalExceptionHandlingMiddleware>();
    }
}

Pattern 4: Custom Exceptions

Define domain-specific exceptions for different error scenarios.

// Base exception
public abstract class DomainException : Exception
{
    protected DomainException(string message) : base(message) { }
    protected DomainException(string message, Exception inner) : base(message, inner) { }
}

// Not Found
public class NotFoundException : DomainException
{
    public NotFoundException(string entityType, object id)
        : base($"{entityType} with id '{id}' was not found.") { }

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

// Validation
public class ValidationException : DomainException
{
    public IReadOnlyDictionary<string, string[]> Errors { get; }

    public ValidationException(IDictionary<string, string[]> errors)
        : base("Validation failed")
    {
        Errors = new ReadOnlyDictionary<string, string[]>(errors);
    }

    public ValidationException(string propertyName, string errorMessage)
        : base("Validation failed")
    {
        Errors = new ReadOnlyDictionary<string, string[]>(
            new Dictionary<string, string[]> { [propertyName] = new[] { errorMessage } });
    }
}

// Conflict
public class ConflictException : DomainException
{
    public ConflictException(string message) : base(message) { }
}

// Business Rule Violation
public class BusinessRuleException : DomainException
{
    public string RuleCode { get; }

    public BusinessRuleException(string ruleCode, string message)
        : base(message)
    {
        RuleCode = ruleCode;
    }
}

Pattern 5: ProblemDetails API

ASP.NET Core 7+ includes built-in ProblemDetails support.

// Program.cs
builder.Services.AddProblemDetails(options =>
{
    options.CustomizeProblemDetails = ctx =>
    {
        ctx.ProblemDetails.Instance = ctx.HttpContext.Request.Path;
        ctx.ProblemDetails.Extensions["traceId"] = Activity.Current?.Id ?? ctx.HttpContext.TraceIdentifier;
        ctx.ProblemDetails.Extensions["timestamp"] = DateTimeOffset.UtcNow;

        if (ctx.HttpContext.User.Identity?.IsAuthenticated == true)
        {
            ctx.ProblemDetails.Extensions["userId"] = ctx.HttpContext.User.Identity.Name;
        }
    };
});

var app = builder.Build();
app.UseExceptionHandler();
app.UseStatusCodePages();

Custom ProblemDetails Factory

public class CustomProblemDetailsFactory : ProblemDetailsFactory
{
    public override ProblemDetails CreateProblemDetails(
        HttpContext httpContext,
        int? statusCode = null,
        string? title = null,
        string? type = null,
        string? detail = null,
        string? instance = null)
    {
        var problemDetails = new ProblemDetails
        {
            Status = statusCode ?? 500,
            Title = title,
            Type = type,
            Detail = detail,
            Instance = instance ?? httpContext.Request.Path
        };

        // Add correlation ID
        if (httpContext.Request.Headers.TryGetValue("X-Correlation-Id", out var correlationId))
        {
            problemDetails.Extensions["correlationId"] = correlationId.ToString();
        }

        return problemDetails;
    }

    public override ValidationProblemDetails CreateValidationProblemDetails(
        HttpContext httpContext,
        ModelStateDictionary modelStateDictionary,
        int? statusCode = null,
        string? title = null,
        string? type = null,
        string? detail = null,
        string? instance = null)
    {
        var validationProblemDetails = new ValidationProblemDetails(modelStateDictionary)
        {
            Status = statusCode ?? 400,
            Title = title ?? "Validation Failed",
            Type = type,
            Detail = detail,
            Instance = instance ?? httpContext.Request.Path
        };

        return validationProblemDetails;
    }
}

// Register
builder.Services.AddSingleton<ProblemDetailsFactory, CustomProblemDetailsFactory>();

Pattern 6: Handler-Level Exception Handling

public abstract class SafePageModel : PageModel
{
    protected async Task<IActionResult> TryAsync(Func<Task<IActionResult>> action)
    {
        try
        {
            return await action();
        }
        catch (NotFoundException ex)
        {
            TempData["ErrorMessage"] = ex.Message;
            return NotFound();
        }
        catch (ValidationException ex)
        {
            foreach (var error in ex.Errors)
            {
                ModelState.AddModelError(error.Key, string.Join(", ", error.Value));
            }
            return Page();
        }
        catch (ConflictException ex)
        {
            ModelState.AddModelError(string.Empty, ex.Message);
            return Page();
        }
        catch (Exception ex)
        {
            // Log and return generic error
            TempData["ErrorMessage"] = "An unexpected error occurred. Please try again.";
            return RedirectToPage("/Error");
        }
    }
}

// Usage
public class OrderDetailsModel(IOrderService orderService) : SafePageModel
{
    public Order? Order { get; set; }

    public Task<IActionResult> OnGetAsync(Guid id)
    {
        return TryAsync(async () =>
        {
            Order = await orderService.GetAsync(id);
            return Page();
        });
    }
}

Pattern 7: Background Service Exception Handling

public class EmailOutboxProcessor(ILogger<EmailOutboxProcessor> logger) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                await ProcessOutboxAsync(stoppingToken);
            }
            catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
            {
                // Expected during shutdown
                break;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Error processing email outbox");
                // Wait before retrying
                await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
            }
        }
    }

    private async Task ProcessOutboxAsync(CancellationToken ct)
    {
        // Processing logic here
    }
}

Pattern 8: MediatR Exception Handling Behavior

public class ExceptionHandlingBehavior<TRequest, TResponse>(ILogger<ExceptionHandlingBehavior<TRequest, TResponse>> logger)
    : IPipelineBehavior<TRequest, TResponse>
    where TRequest : IRequest<TResponse>
{
    public async Task<TResponse> Handle(
        TRequest request,
        RequestHandlerDelegate<TResponse> next,
        CancellationToken cancellationToken)
    {
        try
        {
            return await next(cancellationToken);
        }
        catch (DomainException)
        {
            // Domain exceptions are expected - rethrow for handling upstream
            throw;
        }
        catch (Exception ex)
        {
            logger.LogError(ex,
                "Unexpected error handling {RequestName}",
                typeof(TRequest).Name);

            throw new ApplicationException(
                $"Error processing request {typeof(TRequest).Name}", ex);
        }
    }
}

Anti-Patterns

Swallowing Exceptions

// ❌ BAD: Silent failure
try
{
    await _service.DoWorkAsync();
}
catch (Exception)
{
    // Nothing logged, nothing thrown!
}

// ✅ GOOD: Log and either handle or rethrow
catch (Exception ex)
{
    _logger.LogError(ex, "Failed to complete work");
    throw; // Or handle gracefully
}

Catching Generic Exception Too Early

// ❌ BAD: Catching generic exception too early prevents proper handling
try
{
    var user = await _userService.GetAsync(id);
    var order = await _orderService.CreateAsync(user, request);
}
catch (Exception ex) // Catches everything
{
    // Can't distinguish between user not found and order creation failure
}

// ✅ GOOD: Catch specific exceptions where they occur
try
{
    var user = await _userService.GetAsync(id);
}
catch (NotFoundException ex)
{
    return NotFound(ex.Message);
}

try
{
    var order = await _orderService.CreateAsync(user, request);
}
catch (ValidationException ex)
{
    return BadRequest(ex.Errors);
}

Leaking Sensitive Information

// ❌ BAD: Exposing internal details in production
catch (Exception ex)
{
    return Content($"Database connection failed: {ex.StackTrace}");
}

// ✅ GOOD: Generic message in production, details in development
catch (Exception ex)
{
    _logger.LogError(ex, "Internal error");

    if (_env.IsDevelopment())
    {
        return Content(ex.ToString());
    }

    return Content("An error occurred");
}

References

平台分布

Codex

37.29%
按下载量换算40

Claude

28.04%
按下载量换算30

Cursor

19.59%
按下载量换算21

Gemini CLI

9.72%
按下载量换算10

安全审计

Gen Agent Trust Hub

通过

Socket

未通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源安全扫描存在提醒或未通过项,安装前请自行复核。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills