internal-comms
Write internal communications following company formats, including status reports, leadership updates, and newsletters.
ANanthropics/skills203k3,333 new stars in the last 7 days
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).
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 |
Write internal communications following company formats, including status reports, leadership updates, and newsletters.
ANanthropics/skills203k3,333 new stars in the last 7 days
GAgarrytan/gstack143k636 new stars in the last 7 days
ADaddyosmani/agent-skills122k1,627 new stars in the last 7 days
A pre-launch checklist covering monitoring, staged rollouts and rollback plans.
ADaddyosmani/agent-skills122k1,627 new stars in the last 7 days
PApaperclipai/paperclip119k2,120 new stars in the last 7 days
RUruvnet/RuView106k693 new stars in the last 7 days