Skip to content

Error model

An enum that categorises errors.

MemberUse case
FailureDefault / generic failure.
ValidationInput or state failed validation.
NotFoundA requested resource does not exist.
ConflictDuplicate, concurrency violation, or state conflict.
UnauthorizedMissing or invalid authentication.
ForbiddenAuthenticated but insufficient permissions.
UnexpectedUnhandled or unexpected scenario.

A record with three positional properties and optional metadata.

public record Error(string Code, string Message, ErrorType Type = ErrorType.Failure)
PropertyTypeDescription
CodestringMachine-readable identifier, e.g. "user.not_found".
MessagestringHuman-readable description.
TypeErrorTypeCategory. Defaults to Failure.
MetadataIReadOnlyDictionary<string, object?>?Optional key-value data. Set via with expressions.

Each ErrorType has a corresponding static factory:

Error.Failure("op.failed", "Something went wrong.");
Error.Validation("email.invalid", "Email format is invalid.");
Error.NotFound("order.not_found", "Order does not exist.");
Error.Conflict("user.duplicate", "A user with that email already exists.");
Error.Unauthorized("auth.missing", "No credentials provided.");
Error.Forbidden("auth.denied", "You do not have access.");
Error.Unexpected("unhandled", "An unexpected error occurred.");

Attach arbitrary data using with:

var error = Error.Validation("field.required", "Name is required.")
with { Metadata = new Dictionary<string, object?> { ["field"] = "name" } };