Documentation
¶
Overview ¶
Package errors contains generated code by adptool.
Package errors provides enhanced error handling utilities for Go applications. It offers: - Thread-safe multi-error collection - Error chain traversal and inspection - Type-safe error assertions - Contextual error wrapping - Standard error interface compatibility
The package is designed to work seamlessly with standard library errors while providing additional functionality for complex error handling scenarios.
Index ¶
- Constants
- Variables
- func As(err error, target any) bool
- func AsPkgError(err error, target interface{}) bool
- func AssertType[T error](err error) (T, bool)
- func Cause(err error) error
- func CodeString(code ErrorCode) string
- func ContextFrom(err error) (context.Context, bool)
- func ErrorFormatJSON(i []error) string
- func Errorf(format string, args ...interface{}) error
- func Find(err error, fn func(error) bool) error
- func Has(err, target error) bool
- func Is(err, target error) bool
- func IsPkgError(err, target error) bool
- func IsType[T error](err error) bool
- func Join(errs ...error) error
- func MultiAppend(err error, errs ...error) *merr.Error
- func MultiFlatten(err error) error
- func MultiListFormatFunc(es []error) string
- func MultiPrefix(err error, prefix string) error
- func MustAssertType[T error](err error) T
- func New(message string) error
- func NewStdError(text string) error
- func NewWithContext(ctx context.Context, text string) error
- func RegisterCode(code ErrorCode, val string)
- func Unwrap(err error) error
- func UnwrapPkgError(err error) error
- func Value(err error, key interface{}) interface{}
- func Walk(err error, fn WalkFunc) error
- func WithContext(ctx context.Context, err error) error
- func WithMessage(err error, message string) error
- func WithMessagef(err error, format string, args ...interface{}) error
- func WithStack(err error) error
- func Wrap(err error, message string) error
- func Wrapf(err error, format string, args ...interface{}) error
- type ErrorChain
- type ErrorCode
- type ErrorWithCode
- type ErrorWithStack
- type Frame
- type MultiError
- type MultiErrorFormatFunc
- type MultiGroup
- type StackTrace
- type String
- type ThreadSafeMultiError
- func (m *ThreadSafeMultiError) Append(err error)
- func (m *ThreadSafeMultiError) Contains(target error) bool
- func (m *ThreadSafeMultiError) Error() string
- func (m *ThreadSafeMultiError) Errors() []error
- func (m *ThreadSafeMultiError) HasErrors() bool
- func (m *ThreadSafeMultiError) Snapshot() *MultiError
- type WalkFunc
Constants ¶
const ( // Deprecated: ErrorCodeSuccess represents a success code. In Go, `nil` is the idiomatic way to indicate success. // Returning a non-nil error for a successful operation (even with code 0) is an anti-pattern and can lead to incorrect error handling // with standard `if err != nil` checks. This should be used with caution, primarily at application boundaries (e.g., API responses) // and not in general business logic. Prefer returning `nil` for success. ErrorCodeSuccess = ErrorCode(0) // ErrorCodeError represents a generic error code. ErrorCodeError = ErrorCode(1) )
const (
UnsupportedError = String("unsupported error")
)
Variables ¶
var ErrUnsupported = stderr.ErrUnsupported
Functions ¶
func AsPkgError ¶ added in v0.3.20
func AssertType ¶ added in v0.3.20
AssertType checks if the error is of the specified type and returns it. It works with both value and pointer types.
Example:
// For non-pointer types
if e, ok := AssertType[MyError](err); ok {
// Use e which is of type MyError
}
// For pointer types
if e, ok := AssertType[*MyError](err); ok {
// Use e which is of type *MyError
}
func CodeString ¶
func ContextFrom ¶ added in v0.3.20
ContextFrom retrieves the context.Context from an error if it exists. Returns the context and true if found, nil and false otherwise.
Example:
if ctx, ok := ContextFrom(err); ok {
// Use ctx
}
func ErrorFormatJSON ¶
ErrorFormatJSON formats the list of errors as a JSON array of strings. Each error is converted to its string representation using Error().
Parameters:
- i: The list of errors to format.
Returns:
- string: A JSON array string containing the error messages.
Example:
["error 1", "error 2"]
func Find ¶ added in v0.3.20
Find traverses the error chain and returns the first error for which the provided function returns true.
Example:
// Find the first error of a specific type
var target *MyError
if found := Find(err, func(e error) bool {
return As(e, &target)
}); found != nil {
// Handle the found error
}
func Has ¶ added in v0.3.20
Has checks if any error in the chain matches the target error using errors.Is. It's similar to errors.Is but works with error chains.
Example:
if Has(err, io.EOF) {
// Handle EOF error
}
func IsPkgError ¶ added in v0.3.20
func IsType ¶ added in v0.3.20
IsType checks if the error is of the specified type. It's a type-safe alternative to errors.As.
Example:
if IsType[MyError](err) {
// Handle MyError
}
func MultiFlatten ¶ added in v0.3.20
func MultiListFormatFunc ¶ added in v0.3.20
func MultiPrefix ¶ added in v0.3.20
func MustAssertType ¶ added in v0.3.20
MustAssertType is like AssertType but panics if the error is not of the specified type. Use with caution, only when you're certain about the error type.
Example:
// Will panic if err is not of type *MyError e := MustAssertType[*MyError](err)
func NewStdError ¶ added in v0.3.20
func NewWithContext ¶ added in v0.3.20
Helper function to create a new error with context
Example:
err := NewWithContext(context.Background(), "operation failed")
// Add more context
err = fmt.Errorf("additional context: %w", err)
func RegisterCode ¶
func UnwrapPkgError ¶ added in v0.3.20
func Value ¶ added in v0.3.20
func Value(err error, key interface{}) interface{}
Value retrieves a value from the error's context. It traverses the error chain to find a context that contains the key.
Example:
if val := Value(err, "request_id"); val != nil {
// Use val
}
func Walk ¶ added in v0.3.20
Walk traverses the error chain and calls fn for each error in the chain. If fn returns an error, Walk stops and returns that error.
Example:
err := fmt.Errorf("root error")
err = fmt.Errorf("wrapper: %w", err)
err = Walk(err, func(e error) error {
fmt.Println(e)
return nil // Continue walking
})
func WithContext ¶ added in v0.3.20
WithContext adds a context.Context to an error. If the error is nil or context is nil, the original error is returned unchanged.
Example:
ctx := context.WithValue(context.Background(), "request_id", "123")
err := errors.New("operation failed")
err = WithContext(ctx, err)
func WithMessage ¶ added in v0.3.20
func WithMessagef ¶ added in v0.3.20
Types ¶
type ErrorChain ¶ added in v0.3.20
type ErrorChain interface {
// Unwrap returns the next error in the chain or nil if there are no more errors.
Unwrap() error
// Error returns the string representation of the error.
Error() string
}
ErrorChain represents a chain of errors, where each error in the chain can be unwrapped to get the next error. This is compatible with Go 1.13+ error wrapping.
type ErrorCode ¶ added in v0.3.20
type ErrorCode int
type ErrorWithCode ¶ added in v0.3.20
ErrorWithCode is an error that includes an error code.
type ErrorWithStack ¶ added in v0.3.20
type ErrorWithStack interface {
error
// StackTrace returns the stack trace associated with the error.
StackTrace() perr.StackTrace
}
ErrorWithStack is an error that includes a stack trace.
type MultiError ¶
type MultiErrorFormatFunc ¶ added in v0.3.20
type MultiErrorFormatFunc = merr.ErrorFormatFunc
type MultiGroup ¶ added in v0.3.20
type StackTrace ¶ added in v0.3.20
type StackTrace = perr.StackTrace
type String ¶
type String string
type ThreadSafeMultiError ¶
type ThreadSafeMultiError struct {
ErrorFormat MultiErrorFormatFunc
// contains filtered or unexported fields
}
ThreadSafeMultiError provides a thread-safe implementation of a multi-error type. It wraps hashicorp/go-multierror and adds thread safety for concurrent operations.
This type is particularly useful in concurrent scenarios where multiple goroutines may need to append errors to the same collection simultaneously.
Example:
merr := ThreadSafe(nil)
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func(n int) {
defer wg.Done()
if n%2 == 0 {
merr.Append(fmt.Errorf("even error: %d", n))
}
}(i)
}
wg.Wait()
if merr.HasErrors() {
log.Printf("Encountered %d errors: %v", len(merr.Errors()), merr)
}
func ThreadSafe ¶
func ThreadSafe(err error, fns ...MultiErrorFormatFunc) *ThreadSafeMultiError
ThreadSafe creates and initializes a new ThreadSafeMultiError.
Parameters:
- err: An optional initial error (or nil).
- fns: Optional list of MultiErrorFormatFunc to configure formatting. The first function is used as the formatter.
Returns:
- *ThreadSafeMultiError: A new thread-safe multi-error instance.
If no formatter is provided, ErrorFormatJSON is used by default.
Example:
// Create an empty thread-safe multi-error with default JSON formatting
merr := ThreadSafe(nil)
// Create with an initial error and custom formatting
merr := ThreadSafe(io.EOF, func(errs []error) string {
return fmt.Sprintf("Found %d errors: %v", len(errs), errs)
})
func (*ThreadSafeMultiError) Append ¶
func (m *ThreadSafeMultiError) Append(err error)
Append adds an error to the ThreadSafeMultiError collection in a thread-safe manner. If the error is nil, it will be ignored. If the error is a MultiError, its individual errors will be flattened and added to the collection.
This method is safe for concurrent use by multiple goroutines.
func (*ThreadSafeMultiError) Contains ¶ added in v0.3.20
func (m *ThreadSafeMultiError) Contains(target error) bool
Contains checks if any error in the collection matches the target error using errors.Is. It performs a deep equality check by unwrapping errors.
Parameters:
- target: The error to search for in the collection.
Returns:
- bool: true if the target error is found in the collection, false otherwise.
This method is safe for concurrent use by multiple goroutines.
Example:
merr := ThreadSafe(nil) merr.Append(io.EOF) fmt.Println(merr.Contains(io.EOF)) // Output: true
func (*ThreadSafeMultiError) Error ¶
func (m *ThreadSafeMultiError) Error() string
Error returns the string representation of the error collection. The format is determined by the ErrorFormat function (defaults to ErrorFormatJSON).
Returns:
- string: The formatted error string.
This method is safe for concurrent use by multiple goroutines.
func (*ThreadSafeMultiError) Errors ¶
func (m *ThreadSafeMultiError) Errors() []error
Errors returns a copy of the underlying errors slice.
Returns:
- []error: A new slice containing all errors in the collection.
This method is safe for concurrent use by multiple goroutines.
func (*ThreadSafeMultiError) HasErrors ¶
func (m *ThreadSafeMultiError) HasErrors() bool
HasErrors checks if the ThreadSafeMultiError collection contains any errors.
Returns:
- bool: true if there is at least one error in the collection, false otherwise.
This method is safe for concurrent use by multiple goroutines.
func (*ThreadSafeMultiError) Snapshot ¶ added in v0.3.20
func (m *ThreadSafeMultiError) Snapshot() *MultiError
Snapshot creates and returns a new, non-thread-safe copy of the current error collection. The returned MultiError is a snapshot of the errors at the time of the call.
Returns:
- *MultiError: A new MultiError containing a copy of the current errors.
This method is safe for concurrent use by multiple goroutines, but the returned MultiError is not thread-safe.