agentleFS
codewithmukeshcodewithmukesh/dotnet-agent-kit/skills/error-handling/SKILL.md

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

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 rule

    type-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

  • OpenAISkill

    auth

    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

  • dbtlrSkill

    dependencies

    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

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
  1. Very specific:

    When logic is shared by several handlers, or runs in a background job, return a Result<T> and let each caller translate it.

    line 140

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

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

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 } },
        });
    }

    [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 ProblemDetails

Decision Guide

ScenarioRecommendation
Expected failure in an HTTP handlerReturn Problems.* in a TypedResults union
Record missing, or owned by another tenantProblems.NotFound() (404)
Request clashes with current stateProblems.Conflict("<module>.<reason>", ...) (409)
Well-formed request breaks a business ruleProblems.RuleBroken("<module>.<reason>", ...) (422)
Input shape validationFluentValidation validator + the one endpoint filter (400, validation-failed)
Lost optimistic concurrency raceLet DbUpdateConcurrencyException reach the handler; it maps to 409 stale-version
Unexpected crashIExceptionHandler → 500 ProblemDetails, logged, no internals
Shared domain service or background jobResult<T> with the same error codes; translate at the HTTP edge
External service failure you can handleCatch the specific exception, return a coded problem
Existing codebase built on Result<T> everywhereKeep it consistent; map with one extension at the endpoint

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.