Documentation
¶
Overview ¶
Package errorc provides an implementation of an error augmenting a standard library's [error] with additional context.
The With function works similarly to fmt.Errorf but is faster.
BenchmarkWith-8 53965288 21.81 ns/op BenchmarkFmtErrorf-8 7401583 186.7 ns/op
The With function allows wrapping a sentinel error with additional context and later identifying this error using errors.Is.
ErrInvalidInput := New("invalid input") err := With(ErrInvalidInput, Field("field1", "value1"), Field("field2", "value2")) ... if errors.Is(err, ErrInvalidInput) { // Handle the error }
Also, the With function allows wrapping a typed error with additional context and later identifying this error using errors.As.
type ValidationError struct { Message string } func (e *ValidationError) Error() string { return e.Message } err := With(&ValidationError{"invalid input"}, Field("field1", "value1"), Field("field2", "value2")) ... var ve *ValidationError if errors.As(err, &ve) { // Handle the typed error }
Wrapped error [Error] method returns the original error message and non-empty fields in "key: value" format if key is non-empty or as "value" if key is empty.
The Field function is an adaptor for creating error context fields with a key and a value.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Field ¶
func Field(key, value string) field
Field creates a new field with the given key and value. Both key and value are strings.
func New ¶
New creates a new error with the given message. It is a simple wrapper around the standard library's errors.New function.
func With ¶
With returns an error that wraps the given error with additional context. If the provided error is nil, it returns nil. If no non-nil fields are provided, it simply returns the original error. Unwrapping this error will yield the original error.
Example (SentinelError) ¶
// Create a new sentinel error. ErrInvalidInput := New("invalid input") // Wrap the sentinel error with additional context. err := With( ErrInvalidInput, Field("field1", "value1"), Field("field2", "value2"), ) // Identify the error using errors.Is. if errors.Is(err, ErrInvalidInput) { // Handle the invalid input error. fmt.Print("Handled invalid input error: ", err.Error()) }
Output: Handled invalid input error: invalid input, field1: value1, field2: value2
Example (TypedError) ¶
// Create a new error of type ValidationError. err := With( &ValidationError{"invalid input"}, Field("field1", "value1"), Field("field2", "value2"), ) // Identify ValidationError using errors.As. var ve *ValidationError if errors.As(err, &ve) { // Handle ValidationError. fmt.Print("Handled ValidationError: ", err.Error()) }
Output: Handled ValidationError: invalid input, field1: value1, field2: value2
Types ¶
This section is empty.