Files
xerrors/doc.go

44 lines
1.3 KiB
Go
Raw Normal View History

/*
Package xerrors provides structured application errors with stable machine-readable
codes, human-readable messages, cause chaining, and key-value context fields.
Each error carries a [Code] that maps to a well-known category (invalid input,
not found, internal, etc.) and is stable across versions safe to persist,
transmit in API responses, or switch on programmatically.
# Basic usage
err := xerrors.New(xerrors.ErrNotFound, "user not found")
// With cause chaining
err := xerrors.Wrap(xerrors.ErrInternal, "failed to query database", dbErr)
// Convenience constructors
err := xerrors.NotFound("user %s not found", userID)
// Builder pattern
err := xerrors.New(xerrors.ErrInvalidInput, "validation failed").
WithContext("field", "email").
WithContext("tag", "required")
# Cause chaining
[Err.Unwrap] is implemented, so [errors.Is] and [errors.As] walk the full
cause chain:
if errors.Is(err, io.ErrUnexpectedEOF) { ... }
var e *xerrors.Err
if errors.As(err, &e) {
log.Println(e.Code())
}
# Structured logging (duck-typing bridge)
[Err.ErrorCode] and [Err.ErrorContext] satisfy the private interfaces that logz
defines internally. Passing an *Err to logger.Error automatically enriches the
log record with error_code and context fields without xerrors importing logz
or logz importing xerrors.
*/
package xerrors