errors

package module
v1.3.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 6, 2026 License: MIT Imports: 8 Imported by: 38

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

View Source
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)
)
View Source
const (
	UnsupportedError = String("unsupported error")
)

Variables

View Source
var ErrUnsupported = stderr.ErrUnsupported

Functions

func As

func As(err error, target any) bool

func AsPkgError added in v0.3.20

func AsPkgError(err error, target interface{}) bool

func AssertType added in v0.3.20

func AssertType[T error](err error) (T, bool)

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 Cause

func Cause(err error) error

func CodeString

func CodeString(code ErrorCode) string

func ContextFrom added in v0.3.20

func ContextFrom(err error) (context.Context, bool)

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

func ErrorFormatJSON(i []error) string

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 Errorf

func Errorf(format string, args ...interface{}) error

func Find added in v0.3.20

func Find(err error, fn func(error) bool) error

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

func Has(err, target error) bool

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 Is

func Is(err, target error) bool

func IsPkgError added in v0.3.20

func IsPkgError(err, target error) bool

func IsType added in v0.3.20

func IsType[T error](err error) bool

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 Join

func Join(errs ...error) error

func MultiAppend added in v0.3.20

func MultiAppend(err error, errs ...error) *merr.Error

func MultiFlatten added in v0.3.20

func MultiFlatten(err error) error

func MultiListFormatFunc added in v0.3.20

func MultiListFormatFunc(es []error) string

func MultiPrefix added in v0.3.20

func MultiPrefix(err error, prefix string) error

func MustAssertType added in v0.3.20

func MustAssertType[T error](err error) T

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 New

func New(message string) error

func NewStdError added in v0.3.20

func NewStdError(text string) error

func NewWithContext added in v0.3.20

func NewWithContext(ctx context.Context, text string) error

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 RegisterCode(code ErrorCode, val string)

func Unwrap

func Unwrap(err error) error

func UnwrapPkgError added in v0.3.20

func UnwrapPkgError(err error) error

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

func Walk(err error, fn WalkFunc) error

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

func WithContext(ctx context.Context, err error) error

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 WithMessage(err error, message string) error

func WithMessagef added in v0.3.20

func WithMessagef(err error, format string, args ...interface{}) error

func WithStack

func WithStack(err error) error

func Wrap

func Wrap(err error, message string) error

func Wrapf

func Wrapf(err error, format string, args ...interface{}) error

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

func NewCode added in v0.3.20

func NewCode(code int) ErrorCode

NewCode creates a new ErrorCode from an integer.

func (ErrorCode) Code added in v0.3.20

func (ec ErrorCode) Code() int

func (ErrorCode) Error added in v0.3.20

func (ec ErrorCode) Error() string

func (ErrorCode) Is added in v0.3.20

func (ec ErrorCode) Is(err error) bool

Is checks if the target error is an ErrorCode and has the same value. This allows `errors.Is(wrappedErr, someErrorCode)` to work correctly.

func (ErrorCode) String added in v0.3.20

func (ec ErrorCode) String() string

type ErrorWithCode added in v0.3.20

type ErrorWithCode interface {
	error
	// Code returns the error code.
	Code() int
}

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 Frame added in v0.3.20

type Frame = perr.Frame

type MultiError

type MultiError = merr.Error

type MultiErrorFormatFunc added in v0.3.20

type MultiErrorFormatFunc = merr.ErrorFormatFunc

type MultiGroup added in v0.3.20

type MultiGroup = merr.Group

type StackTrace added in v0.3.20

type StackTrace = perr.StackTrace

type String

type String string

func NewString

func NewString(message string) String

NewString creates a new error from a string

func (String) Error

func (s String) Error() string

Error returns the JSON representation of the error

func (String) Is

func (s String) Is(err error) bool

Is checks if the target error is a String error and has the same value. This allows `errors.Is(wrappedErr, someStringError)` to work correctly.

func (String) String

func (s String) String() string

String returns the JSON representation of the error

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.

type WalkFunc added in v0.3.20

type WalkFunc func(error) error

WalkFunc is the type of the function called for each error in the chain. If the function returns a non-nil error, Walk will stop and return that error.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL