Skip to main content

Error API Reference

Complete reference for the Error type.

Type definition

public readonly record struct Error

Error is an immutable value type. All modification methods return new instances.

Properties

PropertyTypeDescription
CodestringMachine-readable error code (e.g. "USER_NOT_FOUND")
MessagestringHuman-readable description
HttpStatusintHTTP status code (e.g. 404)
CategoryErrorCategorySemantic category (e.g. NotFound)
ExtensionsIReadOnlyDictionary<string, object?>Additional metadata
InnerError?Optional inner error for chaining

Static factory methods

MethodHTTP StatusCategory
Validation(message, code?)422Validation
Validation(code, message, extensions)422Validation
NotFound(message, code?)404NotFound
NotFound(code, message, extensions)404NotFound
Unauthorized(message, code?)401Unauthorized
Unauthorized(code, message, extensions)401Unauthorized
Forbidden(message, code?)403Forbidden
Forbidden(code, message, extensions)403Forbidden
Conflict(message, code?)409Conflict
Conflict(code, message, extensions)409Conflict
TooManyRequests(message, code?)429TooManyRequests
TooManyRequests(code, message, extensions)429TooManyRequests
Unexpected(message, code?)500Unexpected
Unexpected(exception, code?)500Unexpected
Custom(httpStatus, code, message, category?)customCustom
Custom(httpStatus, code, message, extensions, category?)customCustom

Instance methods

MethodReturnsDescription
WithMessage(message)ErrorNew Error with a different message
WithCode(code)ErrorNew Error with a different code
WithInner(error)ErrorNew Error with an inner error attached
WithExtensions(extensions)ErrorNew Error with merged extensions

Static default instances

FieldCodeHTTP Status
DefaultNotFoundNOT_FOUND404
DefaultValidationVALIDATION_ERROR422
DefaultUnauthorizedUNAUTHORIZED401
DefaultForbiddenFORBIDDEN403
DefaultConflictCONFLICT409
DefaultUnexpectedUNEXPECTED_ERROR500

ErrorCategory enum

public enum ErrorCategory
{
Validation, // 422
NotFound, // 404
Unauthorized, // 401
Forbidden, // 403
Conflict, // 409
TooManyRequests, // 429
Unexpected, // 500
Custom
}

Examples

// Simple error
var error = Error.NotFound("User not found", "USER_NOT_FOUND");

// Error with extensions
var error = Error.Validation("FIELD_ERRORS", "Validation failed", new
{
fields = new[] { "email", "name" }
});

// Error with inner error
var outer = Error.Unexpected("Save failed", "SAVE_ERROR")
.WithInner(Error.Unexpected("Connection timeout", "DB_TIMEOUT"));

// From an exception
try { /* ... */ }
catch (Exception ex)
{
var error = Error.Unexpected(ex);
// error.Extensions["exceptionType"] == "InvalidOperationException"
}

See also