Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

error-handling

БесплатноБез исполняемых скриптовНе проверен

Error handling for .NET 10: TypedResults unions, ProblemDetails (RFC 9457) with stable codes, FluentValidation filter, IExceptionHandler, Result<T> for…

codewithmukeshот codewithmukesh★ 858 звёзд на GitHub

Об этом скилле

Error Handling

The kit's default follows ADR-008 (modular slices). Full building-block code (Problems, ErrorCodes, the validation filter factory, the exception handler) is in skills/modular-slices/references/building-blocks.md.

Core Principles

  1. Expected failures are return values, not exceptions. "Order not found" or "already cancelled" is a normal outcome. An HTTP handler returns it as part of a TypedResults union, so the compiler checks it and OpenAPI documents it.
  2. Every error is ProblemDetails with a stable code. Clients switch on code, never on detail text. Business errors use <module>.<reason> (orders.already-cancelled); framework and general errors get a code per status (not-found, validation-failed, forbidden).
  3. Exceptions are for the unexpected, and are caught once. A lost database connection or a bug propagates to one IExceptionHandler that logs it and returns a 500 ProblemDetails without internals.
  4. Validate shape at the boundary, rules in the handler. One endpoint filter runs FluentValidation for every request model. Handlers then check business rules only, against real data.
  5. Result<T> is for code that is not an HTTP handler. Shared domain services, background jobs and libraries cannot return HTTP results but still need typed failures.

Patterns

TypedResults unions in handlers

internal sealed class CancelOrderHandler(OrdersDbContext db, TimeProvider clock) : IHandler
{
    public async Task<Results<Ok<OrderResponse>, ProblemHttpResult>> HandleAsync(Guid id, CancellationToken ct)
    {
        if (await db.Orders.FirstOrDefaultAsync(o => o.Id == id, ct) is not { } order)
            return Problems.NotFound();

        if (order.Status == OrderStatus.Cancelled)
            return Problems.Conflict("orders.already-cancelled", "The order is already cancelled.");

        order.Cancel(clock.GetUtcNow());
        await db.SaveChangesAsync(ct);
        return TypedResults.Ok(OrderResponse.From(order));
    }
}

Results<Ok<OrderResponse>, ProblemHttpResult> accepts only those two types; returning anything else does not compile. Minimal APIs read the union and add 200 and the problem response to the OpenAPI document.

The Problems helper

public static partial class Problems
{
    public static ProblemHttpResult NotFound(string? detail = null) => Create(404, ErrorCodes.NotFound, detail);
    public static ProblemHttpResult Conflict(string code, string detail) => Create(409, Checked(code), detail);
    public static ProblemHttpResult RuleBroken(string code, string detail) => Create(422, Checked(code), detail);

    private static ProblemHttpResult Create(int status, string code, string? detail) =>
        TypedResults.Problem(statusCode: status, detail: detail,
            extensions: new Dictionary<string, object?> { ["code"] = code });

    private static string Checked(string code) =>
        ModuleKey().IsMatch(code) ? code
            : throw new ArgumentException($"Error code '{code}' must look like 'orders.already-cancelled'.", nameof(code));

    [GeneratedRegex(@"^[a-z0-9]+(-[a-z0-9]+)*\.[a-z0-9]+(-[a-z0-9]+)*$")]
    private static partial Regex ModuleKey();
}

Status choices: 404 for a missing record (and for another tenant's record, so IDs cannot be probed), 409 when the request clashes with current state, 422 when a well-formed request breaks a business rule, 403 when the caller may not do this.

ProblemDetails for everything else

builder.Services.AddProblemDetails(options => options.CustomizeProblemDetails = context =>
{
    var problem = context.ProblemDetails;
    problem.Extensions.TryAdd("code", ErrorCodes.ForStatus(problem.Status ?? 500));
    problem.Extensions["traceId"] = Activity.Current?.Id ?? context.HttpContext.TraceIdentifier;
});
builder.Services.AddExceptionHandler<UnexpectedErrorHandler>();

app.UseExceptionHandler();
app.UseStatusCodePages();   // 401/403/404 from the framework also become ProblemDetails

One exception handler at the boundary

public sealed partial class UnexpectedErrorHandler(IProblemDetailsService problems, ILogger<UnexpectedErrorHandler> logger)
    : IExceptionHandler
{
    public async ValueTask<bool> TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken)
    {
        var (status, code) = exception is DbUpdateConcurrencyException
            ? (StatusCodes.Status409Conflict, ErrorCodes.StaleVersion)
            : (StatusCodes.Status500InternalServerError, ErrorCodes.ServerError);

        if (status == StatusCodes.Status500InternalServerError)
            LogUnhandled(logger, exception);

        httpContext.Response.StatusCode = status;
        return await problems.TryWriteAsync(new ProblemDetailsContext
        {
            HttpContext = httpContext,
            Exception = exception,
            ProblemDetails = { Status = status, Extensions = { ["code"] = code }
Полный SKILL.md на GitHub

Установить error-handling в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл error-handling?

Error handling for .NET 10: TypedResults unions, ProblemDetails (RFC 9457) with stable codes, FluentValidation filter, IExceptionHandler, Result<T> for non-HTTP code. Use for "TypedResults", "ProblemDetails", "error code", "Result<T>", "global exception handler", "FluentValidation". Do NOT use for routing (use minimal-api), retries (use resilience), or log output (use logging).

Как установить скилл error-handling?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл error-handling запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить error-handling с