ex

package
v1.20240719.1 Latest Latest
Warning

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

Go to latest
Published: Jul 19, 2024 License: MIT Imports: 7 Imported by: 18

Documentation

Overview

Package ex provides the foundations for error handling in the SDK tree.

To create an error that includes a given string class and stack trace:

err := ex.New("this is a structured error")
...
fmt.Println(ex.ErrStackTrace(err))

When in doubt, wrap any errors from non-sdk methods with an exception:

res, err := http.Get(...)
if err != nil {
	return nil, ex.New(err) // stack trace will originate from this call
}

To create an error from a known error class, that can be used later to check the type of the error:

var ErrTooManyFoos ex.Class = "too many foos"
...
err := ex.New(ErrTooManyFoos)
...
if ex.Is(err, ErrTooManyFoos) { // we can now verify the type of the err with `ex.Is(err, class)`
	fmt.Println("We did too many foos!")
}

We can pass other options to the `ex.New(...)` constructor, such as setting an inner error:

err := ex.New(ErrValidation, ex.OptInner(err))
...
if ex.Is(err, ErrValidation) {
	fmt.Printf("validation error: %v\n", ex.ErrInner(err))
}

Index

Constants

View Source
const (
	DefaultStartDepth    = 3
	DefaultNewStartDepth = 4
)

Defaults for start depth.

Variables

This section is empty.

Functions

func Append

func Append(err error, errs ...error) error

Append appends errors together, creating a multi-error.

func ErrClass

func ErrClass(err interface{}) error

ErrClass returns the exception class or the error message. This depends on if the err is itself an exception or not.

func ErrInner

func ErrInner(err interface{}) error

ErrInner returns an inner error if the error is an ex.

func ErrMessage

func ErrMessage(err interface{}) string

ErrMessage returns the exception message. This depends on if the err is itself an exception or not. If it is not an exception, this will return empty string.

func GetStackTrace

func GetStackTrace() string

GetStackTrace is a utility method to get the current stack trace at call time.

func Is deprecated

func Is(err error, cause error) bool

Is is a helper function that returns if an error is an ex.

It will handle if the err is an exception, a multi-error or a regular error. "Isness" is evaluated by if the class of the exception matches the class of the cause.

Deprecated: Use errors.Is. Make sure `Is()` and `Unwrap()` are properly implemented on your custom classes.

func Nest

func Nest(err ...error) error

Nest nests an arbitrary number of exceptions.

Types

type Class

type Class string

Class is a string wrapper that implements `error`. Use this to implement constant exception causes.

func (Class) Error

func (c Class) Error() string

Class implements `error`.

func (Class) MarshalJSON

func (c Class) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

type ClassProvider

type ClassProvider interface {
	Class() error
}

ClassProvider is a type that can return an exception class.

type Ex

type Ex struct {
	// Class disambiguates between errors, it can be used to identify the type of the error.
	Class error
	// Message adds further detail to the error, and shouldn't be used for disambiguation.
	Message string
	// Inner holds the original error in cases where we're wrapping an error with a stack trace.
	Inner error
	// StackTrace is the call stack frames used to create the stack output.
	StackTrace StackTrace
}

Ex is an error with a stack trace. It also can have an optional cause, it implements `Exception`

func As deprecated

func As(err interface{}) *Ex

As is a helper method that returns an error as an ex.

Deprecated: Use errors.As with *Ex. Make sure `As()` and `Unwrap()` are properly implemented on your custom classes.

func (*Ex) As added in v1.20210615.7

func (e *Ex) As(target interface{}) bool

As delegates to the errors.As to match on the Ex class.

func (*Ex) Decompose

func (e *Ex) Decompose() map[string]interface{}

Decompose breaks the exception down to be marshaled into an intermediate format.

func (*Ex) Error

func (e *Ex) Error() string

Error implements the `error` interface. It returns the exception class, without any of the other supporting context like the stack trace. To fetch the stack trace, use .String().

func (*Ex) Format

func (e *Ex) Format(s fmt.State, verb rune)

Format allows for conditional expansion in printf statements based on the token and flags used.

%+v : class + message + stack
%v, %c : class
%m : message
%t : stack

func (*Ex) Is added in v1.20210615.7

func (e *Ex) Is(target error) bool

Is returns true if the target error matches the Ex. Enables errors.Is on Ex classes when an error is wrapped using Ex.

func (*Ex) MarshalJSON

func (e *Ex) MarshalJSON() ([]byte, error)

MarshalJSON is a custom json marshaler.

func (*Ex) String

func (e *Ex) String() string

String returns a fully formed string representation of the ex. It's equivalent to calling sprintf("%+v", ex).

func (*Ex) UnmarshalJSON

func (e *Ex) UnmarshalJSON(contents []byte) error

UnmarshalJSON is a custom json unmarshaler.

func (*Ex) Unwrap added in v1.20210615.7

func (e *Ex) Unwrap() error

Unwrap returns the inner error if it exists. Enables error chaining and calling errors.Is/As to match on inner errors.

func (*Ex) WithInner

func (e *Ex) WithInner(err error) Exception

WithInner sets the inner ex. Deprecation notice: This method is included as a migraition path from v2, and will be removed after v3.

func (*Ex) WithMessage

func (e *Ex) WithMessage(args ...interface{}) Exception

WithMessage sets the exception message. Deprecation notice: This method is included as a migraition path from v2, and will be removed after v3.

func (*Ex) WithMessagef

func (e *Ex) WithMessagef(format string, args ...interface{}) Exception

WithMessagef sets the exception message based on a format and arguments. Deprecation notice: This method is included as a migration path from v2, and will be removed after v3.

type Exception

type Exception interface {
	error
	WithMessage(...interface{}) Exception
	WithMessagef(string, ...interface{}) Exception
	WithInner(error) Exception
}

Exception is a meta interface for exceptions.

func New

func New(class interface{}, options ...Option) Exception

New returns a new exception with a call stack. Pragma: this violates the rule that you should take interfaces and return concrete types intentionally; it is important for the semantics of typed pointers and nil for this to return an interface because (*Ex)(nil) != nil, but (error)(nil) == nil.

func NewWithStackDepth

func NewWithStackDepth(class interface{}, startDepth int, options ...Option) Exception

NewWithStackDepth creates a new exception with a given start point of the stack.

type Frame

type Frame uintptr

Frame represents a program counter inside a stack frame.

func (Frame) File

func (f Frame) File() string

File returns the full path to the file that contains the function for this Frame's pc.

func (Frame) Format

func (f Frame) Format(s fmt.State, verb rune)

Format formats the frame according to the fmt.Formatter interface.

%s    source file
%d    source line
%n    function name
%v    equivalent to %s:%d

Format accepts flags that alter the printing of some verbs, as follows:

%+s   path of source file relative to the compile time GOPATH
%+v   equivalent to %+s:%d

func (Frame) Func

func (f Frame) Func() string

Func returns the func name.

func (Frame) Line

func (f Frame) Line() int

Line returns the line number of source code of the function for this Frame's pc.

func (Frame) PC

func (f Frame) PC() uintptr

PC returns the program counter for this frame; multiple frames may have the same PC value.

type InnerProvider

type InnerProvider interface {
	Inner() error
}

InnerProvider is a type that returns an inner error.

type MessageProvider added in v1.20240719.1

type MessageProvider interface {
	Message() string
}

MessageProvider is a type that returns a message

type Multi

type Multi []error

Multi represents an array of errors.

func (Multi) Error

func (m Multi) Error() string

Error implements error.

func (Multi) FullError added in v1.20240719.1

func (m Multi) FullError() string

FullError returns the full error message.

func (Multi) Unwrap

func (m Multi) Unwrap() []error

Unwrap returns all the errors in the multi error (basically itself)

type Option

type Option func(*Ex)

Option is an exception option.

func OptInner

func OptInner(inner error) Option

OptInner sets an inner or wrapped ex.

func OptInnerClass

func OptInnerClass(inner error) Option

OptInnerClass sets an inner unwrapped exception. Use this if you don't want to include a strack trace for a cause.

func OptMessage

func OptMessage(args ...interface{}) Option

OptMessage sets the exception message from a given list of arguments with fmt.Sprint(args...).

func OptMessagef

func OptMessagef(format string, args ...interface{}) Option

OptMessagef sets the exception message from a given list of arguments with fmt.Sprintf(format, args...).

func OptStackTrace

func OptStackTrace(stack StackTrace) Option

OptStackTrace sets the exception stack.

type StackPointers

type StackPointers []uintptr

StackPointers is stack of uintptr stack frames from innermost (newest) to outermost (oldest).

func Callers

func Callers(startDepth int) StackPointers

Callers returns stack pointers.

func (StackPointers) Format

func (st StackPointers) Format(s fmt.State, verb rune)

Format formats the stack trace.

func (StackPointers) MarshalJSON

func (st StackPointers) MarshalJSON() ([]byte, error)

MarshalJSON is a custom json marshaler.

func (StackPointers) String

func (st StackPointers) String() string

String returns a single string representation of the stack pointers.

func (StackPointers) Strings

func (st StackPointers) Strings() []string

Strings dereferences the StackTrace as a string slice

type StackStrings

type StackStrings []string

StackStrings represents a stack trace as string literals.

func (StackStrings) Format

func (ss StackStrings) Format(s fmt.State, verb rune)

Format formats the stack trace.

func (StackStrings) MarshalJSON

func (ss StackStrings) MarshalJSON() ([]byte, error)

MarshalJSON is a custom json marshaler.

func (StackStrings) String

func (ss StackStrings) String() string

String returns a single string representation of the stack pointers.

func (StackStrings) Strings

func (ss StackStrings) Strings() []string

Strings returns the stack strings as a string slice.

type StackTrace

type StackTrace interface {
	fmt.Formatter
	Strings() []string
	String() string
}

StackTrace is a stack trace provider.

func ErrStackTrace

func ErrStackTrace(err interface{}) StackTrace

ErrStackTrace returns the exception stack trace. This depends on if the err is itself an exception or not.

type StackTraceProvider

type StackTraceProvider interface {
	StackTrace() StackTrace
}

StackTraceProvider is a type that can return an exception class.

Jump to

Keyboard shortcuts

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