Documentation
¶
Overview ¶
Package xerrors provides a structured, composable error type for Go applications.
The main type in this package is Error, which encapsulates both human-readable and machine-readable error information. It is designed to make error handling, classification, propagation, and tracing consistent and structured across applications and services.
Error allows attaching metadata, structured details, unique IDs, status, and inner wrapped errors. It also provides convenience methods for building, cloning, comparing, and querying errors.
Features of xerrors.Error:
- ID: a stable identifier for the error type (xerrors.ID).
- UID: a unique occurrence identifier (xerrors.UID) for individual instances.
- Message: optional human-readable message (xerrors.Message), which can be templated with dynamic data.
- Details: arbitrary structured key/value data (xerrors.Details) for diagnostics, logging, or observability.
- Status: categorical severity/type (xerrors.Status) such as Failed, Error, Fatal.
- Meta: arbitrary structured metadata (xerrors.Meta), often including operational, domain, or contextual attributes such as Kind, Realm, Operation.
- Err: an underlying wrapped error (standard Go error), excluded from JSON.
The package also provides convenient constructors, methods for cloning, error comparisons, and helpers for setting or querying metadata.
Example usage:
err := xerrors.NewError("database timeout", xerrors.StatusError)
err = err.SetMeta("operation", xerrors.NewOperation("DBQuery"))
if err.IsStatus(xerrors.StatusError) {
log.Println(err.Error())
}
// Wrap an existing error
original := errors.New("disk full")
wrapped := xerrors.NewErrorWrap(original, xerrors.StatusFatal)
// Clone for modification
cloned := wrapped.Clone()
cloned.SetDetails("disk", "/dev/sda1")
Index ¶
- type Details
- func (d Details) Any(key string) (any, bool)
- func (d Details) AnyOr(key string, def any) any
- func (d Details) Bool(key string) (bool, bool)
- func (d Details) BoolOr(key string, def bool) bool
- func (d Details) Clone() Details
- func (d Details) Duration(key string) (time.Duration, bool)
- func (d Details) DurationOr(key string, def time.Duration) time.Duration
- func (d Details) Float32(key string) (float32, bool)
- func (d Details) Float32Or(key string, def float32) float32
- func (d Details) Float64(key string) (float64, bool)
- func (d Details) Float64Or(key string, def float64) float64
- func (d Details) Int(key string) (int, bool)
- func (d Details) Int8(key string) (int8, bool)
- func (d Details) Int8Or(key string, def int8) int8
- func (d Details) Int16(key string) (int16, bool)
- func (d Details) Int16Or(key string, def int16) int16
- func (d Details) Int32(key string) (int32, bool)
- func (d Details) Int32Or(key string, def int32) int32
- func (d Details) Int64(key string) (int64, bool)
- func (d Details) Int64Or(key string, def int64) int64
- func (d Details) IntOr(key string, def int) int
- func (d Details) Merge(other Details) Details
- func (d Details) MustAny(key string) any
- func (d Details) MustBool(key string) bool
- func (d Details) MustDuration(key string) time.Duration
- func (d Details) MustFloat32(key string) float32
- func (d Details) MustFloat64(key string) float64
- func (d Details) MustInt(key string) int
- func (d Details) MustInt8(key string) int8
- func (d Details) MustInt16(key string) int16
- func (d Details) MustInt32(key string) int32
- func (d Details) MustInt64(key string) int64
- func (d Details) MustString(key string) string
- func (d Details) MustTime(key string) time.Time
- func (d Details) MustUint(key string) uint
- func (d Details) MustUint8(key string) uint8
- func (d Details) MustUint16(key string) uint16
- func (d Details) MustUint32(key string) uint32
- func (d Details) MustUint64(key string) uint64
- func (d Details) String(key string) (string, bool)
- func (d Details) StringOr(key string, def string) string
- func (d Details) Time(key string) (time.Time, bool)
- func (d Details) TimeOr(key string, def time.Time) time.Time
- func (d Details) Uint(key string) (uint, bool)
- func (d Details) Uint8(key string) (uint8, bool)
- func (d Details) Uint8Or(key string, def uint8) uint8
- func (d Details) Uint16(key string) (uint16, bool)
- func (d Details) Uint16Or(key string, def uint16) uint16
- func (d Details) Uint32(key string) (uint32, bool)
- func (d Details) Uint32Or(key string, def uint32) uint32
- func (d Details) Uint64(key string) (uint64, bool)
- func (d Details) Uint64Or(key string, def uint64) uint64
- func (d Details) UintOr(key string, def uint) uint
- func (d Details) With(key string, value any) Details
- type Error
- func (e *Error) As(target any) bool
- func (e *Error) Clone() *Error
- func (e *Error) Error() string
- func (e *Error) Format() string
- func (e *Error) Is(target error) bool
- func (e *Error) IsKind(k Kind) bool
- func (e *Error) IsOperation(op Operation) bool
- func (e *Error) IsRealm(r Realm) bool
- func (e *Error) IsStatus(s Status) bool
- func (e *Error) IsZero() bool
- func (e *Error) SetDetails(key string, value any) *Error
- func (e *Error) SetMeta(key string, value any) *Error
- func (e *Error) String() string
- func (e *Error) Unwrap() error
- func (e *Error) WithDetails(d Details) *Error
- func (e *Error) WithError(err error) *Error
- func (e *Error) WithID(id ID) *Error
- func (e *Error) WithMessage(m Message) *Error
- func (e *Error) WithMessageText(text string) *Error
- func (e *Error) WithMeta(m Meta) *Error
- func (e *Error) WithStatus(s Status) *Error
- func (e *Error) WithUID(uid UID) *Error
- type ID
- type Kind
- type Message
- type Meta
- func (m Meta) Any(key string) (any, bool)
- func (m Meta) AnyOr(key string, def any) any
- func (m Meta) Bool(key string) (bool, bool)
- func (m Meta) BoolOr(key string, def bool) bool
- func (m Meta) Clone() Meta
- func (m Meta) Duration(key string) (time.Duration, bool)
- func (m Meta) DurationOr(key string, def time.Duration) time.Duration
- func (m Meta) Float32(key string) (float32, bool)
- func (m Meta) Float32Or(key string, def float32) float32
- func (m Meta) Float64(key string) (float64, bool)
- func (m Meta) Float64Or(key string, def float64) float64
- func (m Meta) Int(key string) (int, bool)
- func (m Meta) Int8(key string) (int8, bool)
- func (m Meta) Int8Or(key string, def int8) int8
- func (m Meta) Int16(key string) (int16, bool)
- func (m Meta) Int16Or(key string, def int16) int16
- func (m Meta) Int32(key string) (int32, bool)
- func (m Meta) Int32Or(key string, def int32) int32
- func (m Meta) Int64(key string) (int64, bool)
- func (m Meta) Int64Or(key string, def int64) int64
- func (m Meta) IntOr(key string, def int) int
- func (m Meta) Kind() (Kind, bool)
- func (m Meta) KindOr(def Kind) Kind
- func (m Meta) Merge(other Meta) Meta
- func (m Meta) MustAny(key string) any
- func (m Meta) MustBool(key string) bool
- func (m Meta) MustDuration(key string) time.Duration
- func (m Meta) MustFloat32(key string) float32
- func (m Meta) MustFloat64(key string) float64
- func (m Meta) MustInt(key string) int
- func (m Meta) MustInt8(key string) int8
- func (m Meta) MustInt16(key string) int16
- func (m Meta) MustInt32(key string) int32
- func (m Meta) MustInt64(key string) int64
- func (m Meta) MustKind() Kind
- func (m Meta) MustOperation() Operation
- func (m Meta) MustRealm() Realm
- func (m Meta) MustString(key string) string
- func (m Meta) MustTime(key string) time.Time
- func (m Meta) MustUint(key string) uint
- func (m Meta) MustUint8(key string) uint8
- func (m Meta) MustUint16(key string) uint16
- func (m Meta) MustUint32(key string) uint32
- func (m Meta) MustUint64(key string) uint64
- func (m Meta) Operation() (Operation, bool)
- func (m Meta) OperationOr(def Operation) Operation
- func (m Meta) Realm() (Realm, bool)
- func (m Meta) RealmOr(def Realm) Realm
- func (m Meta) String(key string) (string, bool)
- func (m Meta) StringOr(key string, def string) string
- func (m Meta) Time(key string) (time.Time, bool)
- func (m Meta) TimeOr(key string, def time.Time) time.Time
- func (m Meta) Uint(key string) (uint, bool)
- func (m Meta) Uint8(key string) (uint8, bool)
- func (m Meta) Uint8Or(key string, def uint8) uint8
- func (m Meta) Uint16(key string) (uint16, bool)
- func (m Meta) Uint16Or(key string, def uint16) uint16
- func (m Meta) Uint32(key string) (uint32, bool)
- func (m Meta) Uint32Or(key string, def uint32) uint32
- func (m Meta) Uint64(key string) (uint64, bool)
- func (m Meta) Uint64Or(key string, def uint64) uint64
- func (m Meta) UintOr(key string, def uint) uint
- func (m Meta) With(key string, value any) Meta
- func (m Meta) WithKind(value Kind) Meta
- func (m Meta) WithOperation(value Operation) Meta
- func (m Meta) WithRealm(value Realm) Meta
- type Operation
- type Realm
- type Status
- type UID
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Details ¶
Details - represents structured diagnostic or context data associated with an error.
Details is typically stored inside Error.Details and is used to attach arbitrary machine-readable key/value data to an error instance.
It allows attaching contextual information such as:
- Input parameters
- Validation fields
- Internal states
- External identifiers
This makes errors more informative, searchable and suitable for structured logging, tracing systems, and API error responses.
func NewDetails ¶
func NewDetails() Details
NewDetails - creates and returns an empty Details map.
This is a convenience constructor and behaves identically to make(Details), but provides consistency with other constructors in the xerrors package.
Example:
d := NewDetails() d["user_id"] = 42
func (Details) Any ¶
Any - retrieves a value stored under the given key.
It returns the value and a boolean indicating whether the key exists.
Example:
d := NewDetails().With("status", "ok")
v, ok := d.Any("status")
if ok {
fmt.Println(v) // Output: ok
}
func (Details) AnyOr ¶
AnyOr - retrieves a value by key or returns the provided default if not present.
This is useful when working with optional fields.
Example:
d := NewDetails()
timeout := d.AnyOr("timeout", 30).(int)
fmt.Println(timeout) // Output: 30
func (Details) Bool ¶
Bool - retrieves a value from Details and attempts to cast it to bool.
Returns the typed value and true on success, or zero value and false if the key does not exist or type mismatch occurs.
Example:
value, ok := d.Bool("field")
if ok {
fmt.Println(value)
}
func (Details) BoolOr ¶
BoolOr - retrieves a value or returns the provided default.
If the key does not exist or type assertion fails, the provided default value is returned.
Example:
timeout := d.BoolOr("timeout", false)
func (Details) Clone ¶
Clone - creates a deep copy of the Details map.
All keys and values are copied into a new map, but the values themselves are not deep-copied (they remain shared references if they are pointers, slices, or maps).
Example:
original := NewDetails().With("id", 1)
copy := original.Clone()
copy["id"] = 2
fmt.Println(original["id"]) // Output: 1
func (Details) Duration ¶
Duration - retrieves a value from Details and attempts to cast it to time.Duration.
Returns the typed value and true on success, or zero value and false if the key does not exist or type mismatch occurs.
Example:
value, ok := d.Duration("field")
if ok {
fmt.Println(value)
}
func (Details) DurationOr ¶
DurationOr - retrieves a value or returns the provided default.
If the key does not exist or type assertion fails, the provided default value is returned.
Example:
timeout := d.DurationOr("timeout", time.Duration(0))
func (Details) Float32 ¶
Float32 - retrieves a value from Details and attempts to cast it to float32.
Returns the typed value and true on success, or zero value and false if the key does not exist or type mismatch occurs.
Example:
value, ok := d.Float32("field")
if ok {
fmt.Println(value)
}
func (Details) Float32Or ¶
Float32Or - retrieves a value or returns the provided default.
If the key does not exist or type assertion fails, the provided default value is returned.
Example:
timeout := d.Float32Or("timeout", 0)
func (Details) Float64 ¶
Float64 - retrieves a value from Details and attempts to cast it to float64.
Returns the typed value and true on success, or zero value and false if the key does not exist or type mismatch occurs.
Example:
value, ok := d.Float64("field")
if ok {
fmt.Println(value)
}
func (Details) Float64Or ¶
Float64Or - retrieves a value or returns the provided default.
If the key does not exist or type assertion fails, the provided default value is returned.
Example:
timeout := d.Float64Or("timeout", 0)
func (Details) Int ¶
Int - retrieves a value from Details and attempts to cast it to int.
Returns the typed value and true on success, or zero value and false if the key does not exist or type mismatch occurs.
Example:
value, ok := d.Int("field")
if ok {
fmt.Println(value)
}
func (Details) Int8 ¶
Int8 - retrieves a value from Details and attempts to cast it to int8.
Returns the typed value and true on success, or zero value and false if the key does not exist or type mismatch occurs.
Example:
value, ok := d.Int8("field")
if ok {
fmt.Println(value)
}
func (Details) Int8Or ¶
Int8Or - retrieves a value or returns the provided default.
If the key does not exist or type assertion fails, the provided default value is returned.
Example:
timeout := d.Int8Or("timeout", 0)
func (Details) Int16 ¶
Int16 - retrieves a value from Details and attempts to cast it to int16.
Returns the typed value and true on success, or zero value and false if the key does not exist or type mismatch occurs.
Example:
value, ok := d.Int16("field")
if ok {
fmt.Println(value)
}
func (Details) Int16Or ¶
Int16Or - retrieves a value or returns the provided default.
If the key does not exist or type assertion fails, the provided default value is returned.
Example:
timeout := d.Int16Or("timeout", 0)
func (Details) Int32 ¶
Int32 - retrieves a value from Details and attempts to cast it to int32.
Returns the typed value and true on success, or zero value and false if the key does not exist or type mismatch occurs.
Example:
value, ok := d.Int32("field")
if ok {
fmt.Println(value)
}
func (Details) Int32Or ¶
Int32Or - retrieves a value or returns the provided default.
If the key does not exist or type assertion fails, the provided default value is returned.
Example:
timeout := d.Int32Or("timeout", 0)
func (Details) Int64 ¶
Int64 - retrieves a value from Details and attempts to cast it to int64.
Returns the typed value and true on success, or zero value and false if the key does not exist or type mismatch occurs.
Example:
value, ok := d.Int64("field")
if ok {
fmt.Println(value)
}
func (Details) Int64Or ¶
Int64Or - retrieves a value or returns the provided default.
If the key does not exist or type assertion fails, the provided default value is returned.
Example:
timeout := d.Int64Or("timeout", 0)
func (Details) IntOr ¶
IntOr - retrieves a value or returns the provided default.
If the key does not exist or type assertion fails, the provided default value is returned.
Example:
timeout := d.IntOr("timeout", 0)
func (Details) Merge ¶
Merge - merges another Details map into the current instance.
In case of key conflicts, values from the "other" map override existing ones.
If the receiver is nil, it is automatically initialized.
Example:
d1 := NewDetails().With("a", 1)
d2 := NewDetails().With("b", 2)
d1.Merge(d2)
fmt.Println(d1) // Output: map[a:1 b:2]
func (Details) MustAny ¶
MustAny - retrieves a value by key and panics if the key does not exist.
This method should be used when the presence of a key is guaranteed by program logic and missing it indicates a programming error.
Example:
d := NewDetails().With("id", 123)
fmt.Println(d.MustAny("id")) // Output: 123
_ = d.MustAny("missing") // panic
func (Details) MustBool ¶
MustBool - retrieves a value and panics if key is missing or invalid type.
Intended for required fields where absence indicates a programming error.
Example:
id := d.MustBool("id") // panic if missing
func (Details) MustDuration ¶
MustDuration - retrieves a value and panics if key is missing or invalid type.
Intended for required fields where absence indicates a programming error.
Example:
id := d.MustDuration("id") // panic if missing
func (Details) MustFloat32 ¶
MustFloat32 - retrieves a value and panics if key is missing or invalid type.
Intended for required fields where absence indicates a programming error.
Example:
id := d.MustFloat32("id") // panic if missing
func (Details) MustFloat64 ¶
MustFloat64 - retrieves a value and panics if key is missing or invalid type.
Intended for required fields where absence indicates a programming error.
Example:
id := d.MustFloat64("id") // panic if missing
func (Details) MustInt ¶
MustInt - retrieves a value and panics if key is missing or invalid type.
Intended for required fields where absence indicates a programming error.
Example:
id := d.MustInt("id") // panic if missing
func (Details) MustInt8 ¶
MustInt8 - retrieves a value and panics if key is missing or invalid type.
Intended for required fields where absence indicates a programming error.
Example:
id := d.MustInt8("id") // panic if missing
func (Details) MustInt16 ¶
MustInt16 - retrieves a value and panics if key is missing or invalid type.
Intended for required fields where absence indicates a programming error.
Example:
id := d.MustInt16("id") // panic if missing
func (Details) MustInt32 ¶
MustInt32 - retrieves a value and panics if key is missing or invalid type.
Intended for required fields where absence indicates a programming error.
Example:
id := d.MustInt32("id") // panic if missing
func (Details) MustInt64 ¶
MustInt64 - retrieves a value and panics if key is missing or invalid type.
Intended for required fields where absence indicates a programming error.
Example:
id := d.MustInt64("id") // panic if missing
func (Details) MustString ¶
MustString - retrieves a value and panics if key is missing or invalid type.
Intended for required fields where absence indicates a programming error.
Example:
id := d.MustString("id") // panic if missing
func (Details) MustTime ¶
MustTime - retrieves a value and panics if key is missing or invalid type.
Intended for required fields where absence indicates a programming error.
Example:
id := d.MustTime("id") // panic if missing
func (Details) MustUint ¶
MustUint - retrieves a value and panics if key is missing or invalid type.
Intended for required fields where absence indicates a programming error.
Example:
id := d.MustUint("id") // panic if missing
func (Details) MustUint8 ¶
MustUint8 - retrieves a value and panics if key is missing or invalid type.
Intended for required fields where absence indicates a programming error.
Example:
id := d.MustUint8("id") // panic if missing
func (Details) MustUint16 ¶
MustUint16 - retrieves a value and panics if key is missing or invalid type.
Intended for required fields where absence indicates a programming error.
Example:
id := d.MustUint16("id") // panic if missing
func (Details) MustUint32 ¶
MustUint32 - retrieves a value and panics if key is missing or invalid type.
Intended for required fields where absence indicates a programming error.
Example:
id := d.MustUint32("id") // panic if missing
func (Details) MustUint64 ¶
MustUint64 - retrieves a value and panics if key is missing or invalid type.
Intended for required fields where absence indicates a programming error.
Example:
id := d.MustUint64("id") // panic if missing
func (Details) String ¶
String - retrieves a value from Details and attempts to cast it to string.
Returns the typed value and true on success, or zero value and false if the key does not exist or type mismatch occurs.
Example:
value, ok := d.String("field")
if ok {
fmt.Println(value)
}
func (Details) StringOr ¶
StringOr - retrieves a value or returns the provided default.
If the key does not exist or type assertion fails, the provided default value is returned.
Example:
timeout := d.StringOr("timeout", "")
func (Details) Time ¶
Time - retrieves a value from Details and attempts to cast it to time.Time.
Returns the typed value and true on success, or zero value and false if the key does not exist or type mismatch occurs.
Example:
value, ok := d.Time("field")
if ok {
fmt.Println(value)
}
func (Details) TimeOr ¶
TimeOr - retrieves a value or returns the provided default.
If the key does not exist or type assertion fails, the provided default value is returned.
Example:
timeout := d.TimeOr("timeout", time.Time{})
func (Details) Uint ¶
Uint - retrieves a value from Details and attempts to cast it to uint.
Returns the typed value and true on success, or zero value and false if the key does not exist or type mismatch occurs.
Example:
value, ok := d.Uint("field")
if ok {
fmt.Println(value)
}
func (Details) Uint8 ¶
Uint8 - retrieves a value from Details and attempts to cast it to uint8.
Returns the typed value and true on success, or zero value and false if the key does not exist or type mismatch occurs.
Example:
value, ok := d.Uint8("field")
if ok {
fmt.Println(value)
}
func (Details) Uint8Or ¶
Uint8Or - retrieves a value or returns the provided default.
If the key does not exist or type assertion fails, the provided default value is returned.
Example:
timeout := d.Uint8Or("timeout", 0)
func (Details) Uint16 ¶
Uint16 - retrieves a value from Details and attempts to cast it to uint16.
Returns the typed value and true on success, or zero value and false if the key does not exist or type mismatch occurs.
Example:
value, ok := d.Uint16("field")
if ok {
fmt.Println(value)
}
func (Details) Uint16Or ¶
Uint16Or - retrieves a value or returns the provided default.
If the key does not exist or type assertion fails, the provided default value is returned.
Example:
timeout := d.Uint16Or("timeout", 0)
func (Details) Uint32 ¶
Uint32 - retrieves a value from Details and attempts to cast it to uint32.
Returns the typed value and true on success, or zero value and false if the key does not exist or type mismatch occurs.
Example:
value, ok := d.Uint32("field")
if ok {
fmt.Println(value)
}
func (Details) Uint32Or ¶
Uint32Or - retrieves a value or returns the provided default.
If the key does not exist or type assertion fails, the provided default value is returned.
Example:
timeout := d.Uint32Or("timeout", 0)
func (Details) Uint64 ¶
Uint64 - retrieves a value from Details and attempts to cast it to uint64.
Returns the typed value and true on success, or zero value and false if the key does not exist or type mismatch occurs.
Example:
value, ok := d.Uint64("field")
if ok {
fmt.Println(value)
}
func (Details) Uint64Or ¶
Uint64Or - retrieves a value or returns the provided default.
If the key does not exist or type assertion fails, the provided default value is returned.
Example:
timeout := d.Uint64Or("timeout", 0)
func (Details) UintOr ¶
UintOr - retrieves a value or returns the provided default.
If the key does not exist or type assertion fails, the provided default value is returned.
Example:
timeout := d.UintOr("timeout", 0)
func (Details) With ¶
With - adds or updates a key-value pair in the Details map and returns the same instance.
If the Details instance is nil, it is automatically initialized.
This method is intended for fluent-style chaining.
Example:
d := NewDetails().
With("email", "test@example.com").
With("age", 30)
type Error ¶
type Error struct {
// ID is the semantic identifier of the error class.
// Example: "USER_NOT_FOUND", "DB_TIMEOUT".
ID ID `json:"id,omitempty"`
// UID is a unique occurrence identifier (UUID) for tracing.
UID UID `json:"uid,omitempty"`
// Message is an optional human-readable or templated message.
Message *Message `json:"message,omitempty"`
// Details is a map of arbitrary structured key/value pairs for diagnostics.
Details Details `json:"details,omitempty"`
// Status classifies the error by severity/type.
Status Status `json:"status,omitempty"`
// Meta is arbitrary metadata for classification, routing, or context.
Meta Meta `json:"meta,omitempty"`
// Err is an optional underlying error being wrapped.
// This field is excluded from JSON serialization.
Err error `json:"-"`
}
Error represents a structured error with both human-readable and machine-readable fields.
It is the primary error type of the xerrors package. Each Error instance can include:
- ID: logical, semantic identifier of the error class.
- UID: unique identifier of this occurrence.
- Message: human-readable or templated message.
- Details: structured diagnostic key/value pairs.
- Status: error severity/type classification.
- Meta: arbitrary additional metadata.
- Err: optional wrapped underlying error (excluded from JSON).
func New ¶
func New() *Error
New - creates a new Error instance with a unique UID but without setting any other fields like ID, Message, Details, Status, or Meta. Example:
e := New() fmt.Println(e.UID)
func NewError ¶
NewError - creates a new Error with a simple plain-text message and a specified Status. Internally, it wraps the provided message into a standard Go error. Example:
e := NewError("file not found", xerrors.StatusFailed)
fmt.Println(e.Error())
func NewErrorWrap ¶
NewErrorWrap - creates a new Error that wraps another existing Go error and specifies a Status. This method helps preserve the original error while adding structure and categorization. Example:
err := errors.New("connection failed")
e := NewErrorWrap(err, StatusInternal)
fmt.Println(e.Error())
func NewErrorf ¶
NewErrorf - creates a new Error with a formatted message and a specific Status. This method is particularly useful when you want to dynamically inject values into the error message. Example:
e := NewErrorf(StatusBadRequest, "invalid input: %s", input) fmt.Println(e.Error())
func (*Error) As ¶
As - implements type assertion for errors.As, assigning the current Error object to the target pointer if it's compatible. Example:
var target *Error
if e.As(&target) {
fmt.Println(target.UID)
}
func (*Error) Clone ¶
Clone - creates a deep copy of the Error, including Message, Details, and Meta. The underlying wrapped error remains uncloned (shared by reference). Example:
copy := e.Clone() fmt.Println(copy.Format())
func (*Error) Error ¶
Error - implements the standard error interface by returning either the Message string, the wrapped error's string, or a fallback string containing the Error ID if none are available. Example:
fmt.Println(e.Error())
func (*Error) Format ¶
Format - returns a detailed string that includes Status, ID, Meta, and the human-readable message. It's primarily used for logging and diagnostics purposes. Example:
fmt.Println(e.Format())
func (*Error) Is ¶
Is - implements the errors.Is comparison logic, checking whether two Errors have matching IDs or Statuses. Example:
e1 := NewError("msg", xerrors.StatusFailed)
e2 := e1.Clone()
fmt.Println(e1.Is(e2)) // true
func (*Error) IsKind ¶
IsKind - verifies if the Error contains the specified Kind within its Meta field. Returns false if Meta is nil or doesn't contain the required kind. Example:
if e.IsKind(KindValidation) { ... }
func (*Error) IsOperation ¶
IsOperation - determines if the Error has the given Operation stored in its Meta field. Returns false if Meta is nil or lacks the operation attribute. Example:
if e.IsOperation(OpCreate) { ... }
func (*Error) IsRealm ¶
IsRealm - confirms if the Error holds the given Realm inside its Meta field. Returns false if Meta is nil or does not store realm information. Example:
if e.IsRealm(RealmUser) { ... }
func (*Error) IsStatus ¶
IsStatus - checks if the Error matches the given Status. Example:
if e.IsStatus(xerrors.StatusFailed) { ... }
func (*Error) IsZero ¶
IsZero - returns true if the Error is empty (nil) or all key fields are unset. Example:
if e.IsZero() { ... }
func (*Error) SetDetails ¶
SetDetails - inserts a single key-value pair into the Details map, initializing it if necessary. Example:
e.SetDetails("field", "invalid")
func (*Error) SetMeta ¶
SetMeta - adds a single key-value pair to the Meta map, creating the map if necessary. Example:
e.SetMeta("key", value)
func (*Error) String ¶
String - is an alias for Error(), providing a readable string representation of the error. Example:
fmt.Println(e.String())
func (*Error) Unwrap ¶
Unwrap - retrieves the underlying wrapped error, if one exists, allowing compatibility with errors.Unwrap. Example:
wrapped := errors.New("disk failure")
e := NewErrorWrap(wrapped, StatusInternal)
fmt.Println(errors.Unwrap(e))
func (*Error) WithDetails ¶
WithDetails - configures the Details map on the Error and returns the updated Error instance. Example:
e := New().WithDetails(details)
func (*Error) WithError ¶
WithError - attaches an underlying error (wrapped error) to the Error instance. Example:
e := New().WithError(errors.New("io error"))
func (*Error) WithID ¶
WithID - sets the ID field on the Error and returns the modified Error instance for chaining. Example:
e := New().WithID(id)
func (*Error) WithMessage ¶
WithMessage - assigns the given Message to the Error and binds the entire Error instance into the message data context under the key "Error".
After calling this method, all fields of Error become available inside the message template and can be referenced via:
{{ .Error.ID }}
{{ .Error.UID }}
{{ .Error.Status }}
{{ .Error.Details }}
{{ .Error.Meta }}
{{ .Error.Err }}
This enables rich, structured message templates without duplicating or copying data into the message.
The method returns the same Error instance to allow fluent chaining.
Example:
e := New().
WithStatus(StatusFailed).
WithMessage(NewMessage("{{ .Error.ID }}: failed login '{{ .user }}' ").With("user", "admin"))
func (*Error) WithMessageText ¶
WithMessageText - sets the Message using a plain string instead of constructing a full Message object. Example:
e := New().WithMessageText("something went wrong")
func (*Error) WithMeta ¶
WithMeta - updates the Meta map associated with the Error and returns the updated Error instance. Example:
e := New().WithMeta(meta)
func (*Error) WithStatus ¶
WithStatus - changes the Status field on the Error and returns the updated Error instance. Example:
e := New().WithStatus(xerrors.StatusFailed)
type ID ¶
type ID string
ID - represents a semantic, human-readable identifier for an error class.
ID is typically used as Error.ID and defines the logical category or identity of an error (not a unique instance).
Examples of common IDs:
- "USER_NOT_FOUND"
- "DB_TIMEOUT"
- "PERMISSION_DENIED"
ID is intended for:
- Machine classification
- Error grouping
- Metrics aggregation
- Routing and filtering
It should be stable, predictable, and meaningful across versions.
type Kind ¶
type Kind string
Kind - represents a semantic classification or category of an error.
Kind is typically stored in Error.Meta to indicate the type or domain of the error (e.g., validation, system, business logic). This allows error filtering, routing, or specialized handling.
Example:
k := NewKind("validation")
fmt.Println(k) // Output: validation
func NewKind ¶
NewKind - creates a new Kind from a string value.
Example:
k := NewKind("authentication")
fmt.Println(k) // Output: authentication
type Message ¶
type Message struct {
// Template - stores the raw message template.
//
// It may contain text/template placeholders such as:
//
// "invalid field {{.field}}"
//
Template string
// Data - stores named template variables.
//
// Map keys correspond to placeholders inside the template.
// Values may be any type supported by text/template.
//
// Example:
//
// Data: map[string]any{"id": 42}
//
Data map[string]any
}
Message - represents a lazily rendered, template-based error message.
Message is designed for structured and dynamic error descriptions. It allows you to define a message template and fill it with runtime data.
The template syntax is compatible with Go's "text/template" package.
Example template:
"User {{.user_id}} not found"
Rendering replaces placeholders using Message.Data.
Message is commonly used as Error.Message and supports:
- Lazy rendering
- Structured data injection
- Cloning
- JSON serialization
When marshaled to JSON, Message is represented as a fully rendered string.
Example usage:
msg := NewMessage("User {{.id}} not found").
With("id", 42)
fmt.Println(msg.String()) // Output: User 42 not found
func NewMessage ¶
NewMessage - creates a new Message from a template string.
This is a convenience constructor that initializes the Template field and returns a pointer for fluent chaining.
Example:
msg := NewMessage("missing field {{.name}}")
func (*Message) Clone ¶
Clone - creates a shallow copy of the Message.
The Template is copied as-is. Data is cloned using maps.Clone to avoid mutation leaks.
If the receiver is nil, Clone returns nil.
Example:
copy := msg.Clone()
func (*Message) MarshalJSON ¶
MarshalJSON - serializes the Message as a rendered string.
This ensures that API consumers always receive a fully formatted message instead of a template with placeholders.
Example JSON:
"User 42 not found"
func (*Message) Render ¶
Render - executes the message template using the attached data context and returns the final rendered string.
If the message was attached to an Error via Error.WithMessage, the data context contains a reference to the entire Error object under the key "Error", allowing templates to access all Error fields directly, for example:
{{ .Error.ID }}
{{ .Error.UID }}
{{ .Error.Status }}
{{ .Error.Details }}
{{ .Error.Meta }}
{{ .Error.Err }}
Behavior:
- If Template is empty, Render returns an empty string and nil error
- If no data is provided and the template contains no placeholders, the template is returned as-is
- If template parsing fails, the original template is returned along with the error
- If execution fails, the original template is returned along with the error
This method never panics and always returns a fallback-safe result.
Example:
msg := NewMessage("{{ .Error.ID }}: failed login '{{ .user }}' ").
With("user", "admin")
s, _ := msg.Render()
fmt.Println(s) // Output: failed login: USER_NOT_FOUND
func (*Message) String ¶
String - returns the rendered message string.
Any rendering error is ignored and the raw template may be returned instead. This allows safe usage inside logging, fmt, or errors without propagation.
Example:
fmt.Println(msg.String())
func (*Message) UnmarshalJSON ¶
UnmarshalJSON - deserializes a JSON string into Message.Template.
NOTE:
- Only the template string is restored.
- Data is always reset to nil.
- This makes Message effectively immutable when loaded from JSON.
Example:
var m Message _ = json.Unmarshal([]byte(`"Access denied"`), &m)
type Meta ¶
Meta - represents structured semantic metadata attached to an error.
Meta stores categorical and semantic attributes of an error, such as:
- Operation — what action was being performed
- Kind — what type of error occurred
- Realm — in which subsystem/domain it happened
Meta is conceptually different from Details:
- Meta is semantic and categorical
- Details is diagnostic and contextual
Meta is typically stored in Error.Meta and is used for:
- Error routing
- Log classification
- Metrics labeling
- Alert grouping
- Filtering and dashboards
All keys are plain strings, defined by convention.
Reserved keys:
- "kind" → Kind
- "realm" → Realm
- "operation" → Operation
Example usage:
meta := NewMeta().
WithKind(NewKind("validation")).
WithRealm(NewRealm("user")).
WithOperation(NewOperation("create"))
All methods support fluent chaining.
func NewMeta ¶
func NewMeta() Meta
NewMeta - creates and returns an empty Meta map.
This is a convenience constructor and behaves the same as make(Meta), but provides consistency across the xerrors package.
Example:
meta := NewMeta()
func (Meta) Any ¶
Any - retrieves the value stored under the specified key.
Returns the value and a boolean indicating its presence.
Example:
v, ok := meta.Any("realm")
func (Meta) AnyOr ¶
AnyOr - retrieves the value by key or returns the default value.
Example:
kind := meta.AnyOr("kind", NewKind("unknown")).(Kind)
func (Meta) Bool ¶
Bool - retrieves a value from Meta and attempts to cast it to bool.
Returns the typed value and true on success, or zero value and false if the key does not exist or type mismatch occurs.
Example:
value, ok := m.Bool("field")
if ok {
fmt.Println(value)
}
func (Meta) BoolOr ¶
BoolOr - retrieves a value or returns the provided default.
If the key does not exist or type assertion fails, the provided default value is returned.
Example:
timeout := m.BoolOr("timeout", false)
func (Meta) Clone ¶
Clone - creates a shallow copy of the Meta map.
All keys and values are copied into a new map, but contained values themselves are not deep copied.
Example:
original := NewMeta().WithKind("db")
copy := original.Clone()
func (Meta) Duration ¶
Duration - retrieves a value from Meta and attempts to cast it to time.Duration.
Returns the typed value and true on success, or zero value and false if the key does not exist or type mismatch occurs.
Example:
value, ok := m.Duration("field")
if ok {
fmt.Println(value)
}
func (Meta) DurationOr ¶
DurationOr - retrieves a value or returns the provided default.
If the key does not exist or type assertion fails, the provided default value is returned.
Example:
timeout := m.DurationOr("timeout", time.Duration(0))
func (Meta) Float32 ¶
Float32 - retrieves a value from Meta and attempts to cast it to float32.
Returns the typed value and true on success, or zero value and false if the key does not exist or type mismatch occurs.
Example:
value, ok := m.Float32("field")
if ok {
fmt.Println(value)
}
func (Meta) Float32Or ¶
Float32Or - retrieves a value or returns the provided default.
If the key does not exist or type assertion fails, the provided default value is returned.
Example:
timeout := m.Float32Or("timeout", 0)
func (Meta) Float64 ¶
Float64 - retrieves a value from Meta and attempts to cast it to float64.
Returns the typed value and true on success, or zero value and false if the key does not exist or type mismatch occurs.
Example:
value, ok := m.Float64("field")
if ok {
fmt.Println(value)
}
func (Meta) Float64Or ¶
Float64Or - retrieves a value or returns the provided default.
If the key does not exist or type assertion fails, the provided default value is returned.
Example:
timeout := m.Float64Or("timeout", 0)
func (Meta) Int ¶
Int - retrieves a value from Meta and attempts to cast it to int.
Returns the typed value and true on success, or zero value and false if the key does not exist or type mismatch occurs.
Example:
value, ok := m.Int("field")
if ok {
fmt.Println(value)
}
func (Meta) Int8 ¶
Int8 - retrieves a value from Meta and attempts to cast it to int8.
Returns the typed value and true on success, or zero value and false if the key does not exist or type mismatch occurs.
Example:
value, ok := m.Int8("field")
if ok {
fmt.Println(value)
}
func (Meta) Int8Or ¶
Int8Or - retrieves a value or returns the provided default.
If the key does not exist or type assertion fails, the provided default value is returned.
Example:
timeout := m.Int8Or("timeout", 0)
func (Meta) Int16 ¶
Int16 - retrieves a value from Meta and attempts to cast it to int16.
Returns the typed value and true on success, or zero value and false if the key does not exist or type mismatch occurs.
Example:
value, ok := m.Int16("field")
if ok {
fmt.Println(value)
}
func (Meta) Int16Or ¶
Int16Or - retrieves a value or returns the provided default.
If the key does not exist or type assertion fails, the provided default value is returned.
Example:
timeout := m.Int16Or("timeout", 0)
func (Meta) Int32 ¶
Int32 - retrieves a value from Meta and attempts to cast it to int32.
Returns the typed value and true on success, or zero value and false if the key does not exist or type mismatch occurs.
Example:
value, ok := m.Int32("field")
if ok {
fmt.Println(value)
}
func (Meta) Int32Or ¶
Int32Or - retrieves a value or returns the provided default.
If the key does not exist or type assertion fails, the provided default value is returned.
Example:
timeout := m.Int32Or("timeout", 0)
func (Meta) Int64 ¶
Int64 - retrieves a value from Meta and attempts to cast it to int64.
Returns the typed value and true on success, or zero value and false if the key does not exist or type mismatch occurs.
Example:
value, ok := m.Int64("field")
if ok {
fmt.Println(value)
}
func (Meta) Int64Or ¶
Int64Or - retrieves a value or returns the provided default.
If the key does not exist or type assertion fails, the provided default value is returned.
Example:
timeout := m.Int64Or("timeout", 0)
func (Meta) IntOr ¶
IntOr - retrieves a value or returns the provided default.
If the key does not exist or type assertion fails, the provided default value is returned.
Example:
timeout := m.IntOr("timeout", 0)
func (Meta) Kind ¶
Kind - retrieves the Kind field from Meta.
Returns the value and a boolean indicating existence and type validity.
Example:
k, ok := meta.Kind()
func (Meta) KindOr ¶
KindOr - retrieves Kind or returns a default value.
Example:
k := meta.KindOr(NewKind("unknown"))
func (Meta) Merge ¶
Merge - merges another Meta map into the current instance.
In case of key collisions, values from "other" override existing ones.
If the receiver is nil, it is automatically initialized.
Example:
m1 := NewMeta().WithKind("validation")
m2 := NewMeta().WithRealm("user")
m1.Merge(m2)
func (Meta) MustAny ¶
MustAny - retrieves a value by key or panics if it does not exist.
This is intended for cases where presence is guaranteed by program logic and absence indicates a bug.
Example:
op := meta.MustAny("operation").(Operation)
func (Meta) MustBool ¶
MustBool - retrieves a value and panics if key is missing or invalid type.
Intended for required fields where absence indicates a programming error.
Example:
id := m.MustBool("id") // panic if missing
func (Meta) MustDuration ¶
MustDuration - retrieves a value and panics if key is missing or invalid type.
Intended for required fields where absence indicates a programming error.
Example:
id := m.MustDuration("id") // panic if missing
func (Meta) MustFloat32 ¶
MustFloat32 - retrieves a value and panics if key is missing or invalid type.
Intended for required fields where absence indicates a programming error.
Example:
id := m.MustFloat32("id") // panic if missing
func (Meta) MustFloat64 ¶
MustFloat64 - retrieves a value and panics if key is missing or invalid type.
Intended for required fields where absence indicates a programming error.
Example:
id := m.MustFloat64("id") // panic if missing
func (Meta) MustInt ¶
MustInt - retrieves a value and panics if key is missing or invalid type.
Intended for required fields where absence indicates a programming error.
Example:
id := m.MustInt("id") // panic if missing
func (Meta) MustInt8 ¶
MustInt8 - retrieves a value and panics if key is missing or invalid type.
Intended for required fields where absence indicates a programming error.
Example:
id := m.MustInt8("id") // panic if missing
func (Meta) MustInt16 ¶
MustInt16 - retrieves a value and panics if key is missing or invalid type.
Intended for required fields where absence indicates a programming error.
Example:
id := m.MustInt16("id") // panic if missing
func (Meta) MustInt32 ¶
MustInt32 - retrieves a value and panics if key is missing or invalid type.
Intended for required fields where absence indicates a programming error.
Example:
id := m.MustInt32("id") // panic if missing
func (Meta) MustInt64 ¶
MustInt64 - retrieves a value and panics if key is missing or invalid type.
Intended for required fields where absence indicates a programming error.
Example:
id := m.MustInt64("id") // panic if missing
func (Meta) MustKind ¶
MustKind - retrieves the Kind or panics if missing or wrong type.
Example:
k := meta.MustKind()
func (Meta) MustOperation ¶
MustOperation - retrieves the Operation or panics if missing or wrong type.
Example:
op := meta.MustOperation()
func (Meta) MustRealm ¶
MustRealm - retrieves the Realm or panics if missing or wrong type.
Example:
r := meta.MustRealm()
func (Meta) MustString ¶
MustString - retrieves a value and panics if key is missing or invalid type.
Intended for required fields where absence indicates a programming error.
Example:
id := m.MustString("id") // panic if missing
func (Meta) MustTime ¶
MustTime - retrieves a value and panics if key is missing or invalid type.
Intended for required fields where absence indicates a programming error.
Example:
id := m.MustTime("id") // panic if missing
func (Meta) MustUint ¶
MustUint - retrieves a value and panics if key is missing or invalid type.
Intended for required fields where absence indicates a programming error.
Example:
id := m.MustUint("id") // panic if missing
func (Meta) MustUint8 ¶
MustUint8 - retrieves a value and panics if key is missing or invalid type.
Intended for required fields where absence indicates a programming error.
Example:
id := m.MustUint8("id") // panic if missing
func (Meta) MustUint16 ¶
MustUint16 - retrieves a value and panics if key is missing or invalid type.
Intended for required fields where absence indicates a programming error.
Example:
id := m.MustUint16("id") // panic if missing
func (Meta) MustUint32 ¶
MustUint32 - retrieves a value and panics if key is missing or invalid type.
Intended for required fields where absence indicates a programming error.
Example:
id := m.MustUint32("id") // panic if missing
func (Meta) MustUint64 ¶
MustUint64 - retrieves a value and panics if key is missing or invalid type.
Intended for required fields where absence indicates a programming error.
Example:
id := m.MustUint64("id") // panic if missing
func (Meta) Operation ¶
Operation - retrieves the Operation field from Meta.
Example:
op, ok := meta.Operation()
func (Meta) OperationOr ¶
OperationOr - retrieves Operation or returns a default value.
Example:
op := meta.OperationOr(NewOperation("unknown"))
func (Meta) RealmOr ¶
RealmOr - retrieves Realm or returns a default value.
Example:
r := meta.RealmOr(NewRealm("unknown"))
func (Meta) String ¶
String - retrieves a value from Meta and attempts to cast it to string.
Returns the typed value and true on success, or zero value and false if the key does not exist or type mismatch occurs.
Example:
value, ok := m.String("field")
if ok {
fmt.Println(value)
}
func (Meta) StringOr ¶
StringOr - retrieves a value or returns the provided default.
If the key does not exist or type assertion fails, the provided default value is returned.
Example:
timeout := m.StringOr("timeout", "")
func (Meta) Time ¶
Time - retrieves a value from Meta and attempts to cast it to time.Time.
Returns the typed value and true on success, or zero value and false if the key does not exist or type mismatch occurs.
Example:
value, ok := m.Time("field")
if ok {
fmt.Println(value)
}
func (Meta) TimeOr ¶
TimeOr - retrieves a value or returns the provided default.
If the key does not exist or type assertion fails, the provided default value is returned.
Example:
timeout := m.TimeOr("timeout", time.Time{})
func (Meta) Uint ¶
Uint - retrieves a value from Meta and attempts to cast it to uint.
Returns the typed value and true on success, or zero value and false if the key does not exist or type mismatch occurs.
Example:
value, ok := m.Uint("field")
if ok {
fmt.Println(value)
}
func (Meta) Uint8 ¶
Uint8 - retrieves a value from Meta and attempts to cast it to uint8.
Returns the typed value and true on success, or zero value and false if the key does not exist or type mismatch occurs.
Example:
value, ok := m.Uint8("field")
if ok {
fmt.Println(value)
}
func (Meta) Uint8Or ¶
Uint8Or - retrieves a value or returns the provided default.
If the key does not exist or type assertion fails, the provided default value is returned.
Example:
timeout := m.Uint8Or("timeout", 0)
func (Meta) Uint16 ¶
Uint16 - retrieves a value from Meta and attempts to cast it to uint16.
Returns the typed value and true on success, or zero value and false if the key does not exist or type mismatch occurs.
Example:
value, ok := m.Uint16("field")
if ok {
fmt.Println(value)
}
func (Meta) Uint16Or ¶
Uint16Or - retrieves a value or returns the provided default.
If the key does not exist or type assertion fails, the provided default value is returned.
Example:
timeout := m.Uint16Or("timeout", 0)
func (Meta) Uint32 ¶
Uint32 - retrieves a value from Meta and attempts to cast it to uint32.
Returns the typed value and true on success, or zero value and false if the key does not exist or type mismatch occurs.
Example:
value, ok := m.Uint32("field")
if ok {
fmt.Println(value)
}
func (Meta) Uint32Or ¶
Uint32Or - retrieves a value or returns the provided default.
If the key does not exist or type assertion fails, the provided default value is returned.
Example:
timeout := m.Uint32Or("timeout", 0)
func (Meta) Uint64 ¶
Uint64 - retrieves a value from Meta and attempts to cast it to uint64.
Returns the typed value and true on success, or zero value and false if the key does not exist or type mismatch occurs.
Example:
value, ok := m.Uint64("field")
if ok {
fmt.Println(value)
}
func (Meta) Uint64Or ¶
Uint64Or - retrieves a value or returns the provided default.
If the key does not exist or type assertion fails, the provided default value is returned.
Example:
timeout := m.Uint64Or("timeout", 0)
func (Meta) UintOr ¶
UintOr - retrieves a value or returns the provided default.
If the key does not exist or type assertion fails, the provided default value is returned.
Example:
timeout := m.UintOr("timeout", 0)
func (Meta) With ¶
With - adds or updates a key-value pair in the Meta map.
If Meta is nil, it is automatically initialized.
This method is intended for fluent-style usage.
Example:
meta := NewMeta().
With("trace_id", "abc-123").
With("shard", 2)
func (Meta) WithKind ¶
WithKind - assigns the Kind semantic attribute.
Shortcut for:
m.With("kind", value)
Example:
meta := NewMeta().WithKind(NewKind("auth"))
func (Meta) WithOperation ¶
WithOperation - assigns the Operation semantic attribute.
Shortcut for:
m.With("operation", value)
Example:
meta := NewMeta().WithOperation(NewOperation("update"))
type Operation ¶
type Operation string
Operation - represents the specific operation or action associated with an error.
Operation is typically stored in Error.Meta to indicate which API call, database operation, or business process triggered the error.
Example:
op := NewOperation("create")
fmt.Println(op) // Output: create
func NewOperation ¶
NewOperation - creates a new Operation from a string value.
Example:
op := NewOperation("update")
fmt.Println(op) // Output: update
func (Operation) Clone ¶
Clone - returns a copy of the Operation.
Example:
op2 := op.Clone() fmt.Println(op2)
type Realm ¶
type Realm string
Realm - represents the domain, subsystem, or context for an error.
Realm is often used in Error.Meta to identify which system area, module, or logical domain the error is associated with (e.g., "user", "payment").
Example:
r := NewRealm("user")
fmt.Println(r) // Output: user
func NewRealm ¶
NewRealm - creates a new Realm from a string value.
Example:
r := NewRealm("order")
fmt.Println(r) // Output: order
type Status ¶
type Status int
Status - represents the severity or type classification of an error.
Status is primarily used by the Error type to categorize errors by their severity level, allowing developers to handle different types of errors differently (e.g., logging, retrying, or terminating execution).
It also provides helper methods for common comparisons and supports JSON serialization/deserialization to facilitate structured logging and API responses.
const ( // StatusUnknown - represents an undefined or unknown status. // // Typically used as a default or placeholder value when an error's // classification has not been explicitly set. StatusUnknown Status = iota // StatusFailed - represents a generic failure that is recoverable or expected. // // Example use case: a network request failed due to a temporary condition, // and retrying may succeed. StatusFailed // StatusError - represents a serious error that requires attention. // // Example use case: invalid user input, failed database query, or misconfigured resource. StatusError // StatusFatal - represents a critical failure that may halt execution. // // Example use case: unrecoverable system failure, corrupted state, or critical dependency failure. StatusFatal )
func (Status) Clone ¶
Clone - returns a copy of the Status value.
Useful when you need to duplicate status values without modifying the original.
Example:
s1 := StatusError s2 := s1.Clone() fmt.Println(s2) // Output: error
func (Status) IsError ¶
IsError - checks whether the Status is StatusError.
Example:
if s.IsError() {
fmt.Println("error requires attention")
}
func (Status) IsFailed ¶
IsFailed - checks whether the Status is StatusFailed.
Example:
if s.IsFailed() {
fmt.Println("operation failed, may retry")
}
func (Status) IsFatal ¶
IsFatal - checks whether the Status is StatusFatal.
Example:
if s.IsFatal() {
fmt.Println("critical failure, aborting")
}
func (Status) IsUnknown ¶
IsUnknown - checks whether the Status is StatusUnknown.
Example:
if s.IsUnknown() {
fmt.Println("status not set")
}
func (Status) MarshalJSON ¶
MarshalJSON - serializes the Status to JSON using its string representation.
This ensures that JSON logs or API responses contain human-readable status names instead of numeric values.
Example:
data, _ := json.Marshal(StatusFatal) fmt.Println(string(data)) // Output: "fatal"
func (Status) String ¶
String - returns the human-readable string representation of the Status.
This is useful for logging, displaying error status in APIs, or formatting error messages.
Example:
fmt.Println(StatusFailed.String()) // Output: "failed"
func (*Status) UnmarshalJSON ¶
UnmarshalJSON - deserializes a JSON string into a Status value.
If the input string is unknown, it defaults to StatusUnknown and returns an error. This allows robust handling of malformed or unexpected data.
Example:
var s Status _ = json.Unmarshal([]byte(`"error"`), &s) fmt.Println(s) // Output: error
type UID ¶
UID - represents a unique identifier of a specific error occurrence.
This allows precise tracing of an error in logs, metrics systems, and across service boundaries.
UID is implemented as a thin wrapper around uuid.UUID.
func (UID) IsZero ¶
IsZero - checks whether the UID is empty (zero UUID).
A zero UID usually indicates that it was never initialized.
Example:
if uid.IsZero() {
fmt.Println("UID not initialized")
}
func (UID) MarshalJSON ¶
MarshalJSON - serializes the UID into JSON as a string.
This ensures that the UID is represented in standard UUID format rather than as raw binary data.
Example:
data, _ := json.Marshal(uid) fmt.Println(string(data))
func (UID) String ¶
String - returns the canonical string representation of the UID.
The format is compatible with standard UUID encoding.
Example:
uid := UID(uuid.New()) fmt.Println(uid.String())
func (UID) UUID ¶
UUID - converts UID into the underlying uuid.UUID type.
This is useful when interacting with APIs or libraries that expect a standard UUID value.
Example:
raw := uid.UUID()
func (*UID) UnmarshalJSON ¶
UnmarshalJSON - deserializes a JSON string into a UID value.
If the JSON value is an empty string, the UID is set to uuid.Nil.
If the input string is not a valid UUID, an error is returned.
Example:
var uid UID _ = json.Unmarshal([]byte(`"550e8400-e29b-41d4-a716-446655440000"`), &uid) fmt.Println(uid.String())