/dotnet-agent-kit:error-handlingfrom dotnet Agent Kit
Provides .NET 10 error handling patterns: TypedResults unions, ProblemDetails (RFC 9457) with stable error codes, FluentValidation filter, IExceptionHandler, and Result<T> for non-HTTP code.
Ships in dotnet Agent Kit. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
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.
TypedResults union, so the compiler checks it and OpenAPI documents it.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).IExceptionHandler that logs it and returns a 500 ProblemDetails without internals.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.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.
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.
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
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 } },
});
}
[LoggerMessage(Level = LogLevel.Error, Message = "Unhandled exception")]
private static partial void LogUnhandled(ILogger logger, Exception exception);
}
A concurrency conflict is the one exception worth mapping: EF Core reports it only by throwing, and the client's answer (reload and retry) is predictable.
internal sealed class PlaceOrderRequestValidator : AbstractValidator<PlaceOrderRequest>
{
public PlaceOrderRequestValidator()
{
RuleFor(r => r.ProductId).NotEmpty();
RuleFor(r => r.Quantity).InclusiveBetween(1, 100);
}
}
// Added once to the API group; validates any parameter that has a registered validator
var api = app.MapGroup("/api/v1")
.AddEndpointFilterFactory(RequestValidation.Create)
.ProducesValidationProblem();
The filter returns TypedResults.ValidationProblem(errors) with code: validation-failed, and field keys in JSON casing (lines[0].quantity). Endpoints without validated parameters get no filter. The full factory is in the modular-slices building blocks.
When logic is shared by several handlers, or runs in a background job, return a Result<T> and let each caller translate it.
public sealed record Error(string Code, string Message);
public readonly record struct Result<T>
{
public T? Value { get; }
public Error? Error { get; }
public bool IsSuccess => Error is null;
private Result(T? value, Error? error) => (Value, Error) = (value, error);
public static Result<T> Success(T value) => new(value, null);
public static Result<T> Failure(Error error) => new(default, error);
public static implicit operator Result<T>(T value) => Success(value);
public static implicit operator Result<T>(Error error) => Failure(error);
}
// A pricing service used by PlaceOrder and the nightly re-pricing job
internal sealed class Pricing(OrdersDbContext db)
{
public async Task<Result<decimal>> PriceAsync(Guid productId, int quantity, CancellationToken ct) =>
await db.Prices.FirstOrDefaultAsync(p => p.ProductId == productId, ct) is { } price
? price.Amount * quantity
: new Error("orders.no-price", "The product has no price.");
}
// In the handler: translate at the edge
var total = await pricing.PriceAsync(request.ProductId, request.Quantity, ct);
if (!total.IsSuccess)
return Problems.RuleBroken(total.Error!.Code, total.Error.Message);
Reusing the <module>.<reason> code in the Error keeps the translation one line.
// BAD: control flow through exceptions, caught and mapped somewhere else
var order = await db.Orders.FindAsync([id], ct) ?? throw new NotFoundException($"Order {id}");
// GOOD: the outcome is part of the signature
if (await db.Orders.FindAsync([id], ct) is not { } order)
return Problems.NotFound();
// BAD: any result compiles, and OpenAPI sees nothing
public async Task<IResult> HandleAsync(Guid id, CancellationToken ct) { /* ... */ }
// GOOD
public async Task<Results<Ok<OrderResponse>, ProblemHttpResult>> HandleAsync(Guid id, CancellationToken ct) { /* ... */ }
// BAD: handler returns Result<T>, endpoint maps it back to HTTP
var result = await handler.HandleAsync(request, ct);
return result.IsSuccess ? TypedResults.Ok(result.Value) : result.ToProblemDetails();
// GOOD: the handler returns the HTTP outcome directly
return await handler.HandleAsync(request, ct);
// BAD
return Results.BadRequest("Something went wrong");
return TypedResults.Problem("Order already cancelled", statusCode: 409);
// GOOD
return Problems.Conflict("orders.already-cancelled", "The order is already cancelled.");
// BAD
try { await ProcessAsync(order, ct); } catch (Exception) { }
// GOOD: catch only what you can handle, and say what happened
try { await gateway.ChargeAsync(order.Id, order.Total, ct); }
catch (PaymentDeclinedException ex)
{
logger.LogWarning(ex, "Payment declined for order {OrderId}", order.Id);
return Problems.RuleBroken("orders.payment-declined", "The payment was declined.");
}
// BAD: stack traces and SQL in production responses
problem.Detail = exception.ToString();
// GOOD: log the exception, return a code and the trace ID
logger.LogError(exception, "Unhandled exception"); // traceId is on the ProblemDetails
| Scenario | Recommendation |
|---|---|
| Expected failure in an HTTP handler | Return Problems.* in a TypedResults union |
| Record missing, or owned by another tenant | Problems.NotFound() (404) |
| Request clashes with current state | Problems.Conflict("<module>.<reason>", ...) (409) |
| Well-formed request breaks a business rule | Problems.RuleBroken("<module>.<reason>", ...) (422) |
| Input shape validation | FluentValidation validator + the one endpoint filter (400, validation-failed) |
| Lost optimistic concurrency race | Let DbUpdateConcurrencyException reach the handler; it maps to 409 stale-version |
| Unexpected crash | IExceptionHandler → 500 ProblemDetails, logged, no internals |
| Shared domain service or background job | Result<T> with the same error codes; translate at the HTTP edge |
| External service failure you can handle | Catch the specific exception, return a coded problem |
Existing codebase built on Result<T> everywhere | Keep it consistent; map with one extension at the endpoint |
What SKILL.md sets; muted values are Claude Code's defaults
37 skills in this plugin
/api-hardeningProduction hardening for ASP.NET Core 10 APIs: HSTS, forwarded headers behind a proxy (KnownIPNetworks), strict CORS, body and upload limits, security headers, no detailed errors. Use for "HSTS", "forwarded headers", "behind nginx", "CORS", "request size limit", "security headers", "harden for production". Do NOT use for auth (use authentication) or throttling (use rate-limiting).
/architecture-advisorArchitecture selection for new or restructured .NET solutions: asks about domain, team and compliance, then recommends modular slices (default), vertical slice, Clean Architecture or DDD. Use for "which architecture", "new solution", "restructure", "DDD", "project structure", "tech stack". Do NOT use for adding features to a modular-slices codebase (modular-slices), scaffolding (scaffold), or CLAUDE.md (dotnet-init).
/aspireAspire (17.x, requires .NET 10) orchestration: AppHost, service defaults, resource configuration, service discovery, dashboard. Use for "Aspire", "AppHost", "service defaults", "service discovery", "AddDotnetProject", "AddProject", "WithReference", "aspire run". Do NOT use for Dockerfiles or container images (use docker), CI/CD pipelines (use ci-cd), or OpenTelemetry SDK setup (use opentelemetry).
/authenticationAuthentication and authorization for ASP.NET Core: JWT bearer, OpenID Connect, ASP.NET Identity, policies, role and claim-based authorization, API keys, cookie auth. Use for "JWT", "OIDC", "Identity", "claims", "roles", "RequireAuthorization", "API key". Do NOT use for endpoint design (use minimal-api), security schemes in API docs (use openapi), secrets and options binding (use configuration), or which rows a user may see (use resource-authorization).
/build-fixAutonomous loop that drives a broken .NET build or failing tests to green, with bounded iterations and retry guards (build, parse, fix, rebuild; test-fix variant). Use for "fix the build", "make it compile", "fix failing tests", "keep going until it works", "auto-fix". Do NOT use for cleanup of code that already builds (use de-sloppify), writing new tests (use testing or tdd), or a pre-PR check (use verify).
/cachingCaching for .NET 10: HybridCache (the default), output caching, response caching, distributed cache. Use for "cache", "HybridCache", "Redis", "output cache", "IMemoryCache", "cache invalidation", "stampede protection". Do NOT use for EF Core query tuning or N+1 (use ef-core), retry and timeout policies (use resilience), or Redis as a message broker (use messaging).
npx claudepluginhub codewithmukesh/dotnet-agent-kit --plugin dotnet-agent-kitOther plugins' skills for the same job