error-handling
Skill853 starsChanged yesterdayMITView on GitHub
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).
86 other projects use a version of this.
Adopted by
Most recently taken up by
- satvikgbusiness-jpg/Claude-skillstheir own version, first seen Nov 29, 2026
- jayavibhavnk/claude-skillstheir own version, first seen Nov 29, 2026
- sandaiwen/doc-spec-frameworktheir own version, first seen Nov 22, 2026
- dreitagebart/skillstheir own version, first seen Nov 22, 2026
- AndresArreguy/ecc-pi-porttheir own version, first seen Nov 16, 2026
- komluk/scaffoldingtheir own version, first seen Nov 15, 2026
Used with
Projects with it also use type-safety, auth and 1 more.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
MANVENDRA-githubCursor ruletype-safety
Python static typing discipline — annotate every signature, run a strict type checker, treat escape hatches as code smells. Apply when working in any Python file. Skip for throwaway scripts and notebooks where the code will not outlive the session.
Also in 3 projects that use this
OpenAISkillauth
Authentication integration guidance — Clerk (native Vercel Marketplace), Descope, and Auth0 setup for Next.js applications. Covers middleware auth patterns, sign-in/sign-up flows, and Marketplace provisioning. Use when implementing user authentication.
Also in 6 projects that use this
dbtlrSkilldependencies
Use when adding, evaluating, or updating Rust crate dependencies. Also use when considering whether to implement something yourself vs pulling in a library.
Also in 4 projects that use this
Other versions86 projects use a version of this.
Word for word · 1
- codewithmukesh/dotnet-claude-kit★ 853100% same
Edited · 0
None found.
Wrote their own version · 85
- microsoft/data-formulator★ 17ksame name
- EpicenterHQ/epicenter★ 4.8ksame name
- epicenter-md/epicenter★ 4.8ksame name
- software-mansion/react-native-executorch★ 1.8ksame name
- CloudAI-X/claude-workflow★ 1.4ksame name
- CloudAI-X/claude-workflow-v2★ 1.4ksame name
- alchemyplatform/aa-sdk★ 321same name
- Resgrid/Core★ 239same name
- DevelopersGlobal/ai-agent-skills★ 220same name
- kid-sid/claude-spellbook★ 190same name
75 more not listed
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository38 other files it gives its agents.
- AGENTS.mdAGENTS.md
- .codex/AGENTS.mdAGENTS.md
- .opencode/AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- .cursor/rules/dotnet-rules.mdCursor rule
- architecture-advisorSkill
- aspireSkill
- authenticationSkill
- build-fixSkill
- cachingSkill
- ci-cdSkill
- code-reviewSkill
- configurationSkill
- console-cliSkill
- dependency-injectionSkill
- desktop-mvvmSkill
- de-sloppifySkill
- dockerSkill
- doctorSkill
- dotnet-initSkill
- ef-coreSkill
- instinct-systemSkill
- loggingSkill
- messagingSkill
- migrateSkill
- minimal-apiSkill
- modern-csharpSkill
- modular-slicesSkill
- native-aotSkill
- openapiSkill
- opentelemetrySkill
- resilienceSkill
- scaffoldSkill
- specSkill
- tddSkill
- testingSkill
- verifySkill
- wrap-upSkill
The file
We split this skill into the rules it gives an agent
1 rule. 0 are common, 0 are distinctive, and 1 is very specific to this project.
0
Common
Most of the 70 edited versions we read keep these.
0
Distinctive
This author's own choices. Worth a look.
1
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 140
When logic is shared by several handlers, or runs in a background job, return a Result<T> and let each caller translate it.
“Common” is measured: kept by at least 6 in 10 of the 70 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
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
- 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
TypedResultsunion, so the compiler checks it and OpenAPI documents it. - Every error is ProblemDetails with a stable
code. Clients switch oncode, never ondetailtext. Business errors use<module>.<reason>(orders.already-cancelled); framework and general errors get a code per status (not-found,validation-failed,forbidden). - Exceptions are for the unexpected, and are caught once. A lost database connection or a bug propagates to one
IExceptionHandlerthat logs it and returns a 500 ProblemDetails without internals. - 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.
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 ProblemDetailsOne 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 } },
});
}
[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.
Validation through one endpoint filter
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.
Result<T> for non-HTTP code
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.
Anti-patterns
Throwing for expected outcomes
// 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();Returning IResult instead of a union
// 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) { /* ... */ }A Result<T> round-trip inside an HTTP slice
// 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);Errors without codes, or with free-text codes
// 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.");Catching and swallowing
// 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.");
}Leaking exception details
// 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 ProblemDetailsDecision Guide
| 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 |
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

