errors

package module
v0.7.2 Latest Latest
Warning

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

Go to latest
Published: Mar 29, 2022 License: BSD-3-Clause Imports: 8 Imported by: 50

README

errors

Latest release Build status Go Report Card Documentation

Package errors contains additional functions, interfaces and structs for recording stack frames, applying basic formatting, working with goroutines, multiple errors and custom error types.

It is inspired by the golang.org/x/xerrors package and is designed to be a drop in replacement for it, as well as the standard library's errors package.

go get github.com/go-pogo/errors
import "github.com/go-pogo/errors"

Stack trace

Every error can track stack trace information. Just wrap it with errors.WithStack and a complete stack trace is captured.

err = errors.WithStack(err)
some error: something happened:
    main.doSomething
       .../errors/examples/2_trace/main.go:17
    main.someAction
       .../errors/examples/2_trace/main.go:12

Formatting

Wrap an existing error with errors.WithFormatter to upgrade the error to include basic formatting. Formatting is done using xerrors.FormatError and thus the same verbs are supported.

fmt.Printf("%+v", errors.WithFormatter(err))

Catch panics

A convenient function is available to catch panics and store them as an error.

var err error
defer errors.CatchPanic(&err)

Documentation

Additional detailed documentation is available at pkg.go.dev

Created with

License

Copyright © 2019-2021 Roel Schut. All rights reserved.

This project is governed by a BSD-style license that can be found in the LICENSE file.

Documentation

Overview

Package errors contains additional functions, interfaces and structs for recording stack frames, applying basic formatting, working with goroutines, multiple errors and custom error types.

It is inspired by package golang.org/x/xerrors and is designed to be a drop-in replacement for it, as well as the standard library's errors package.

The New and Newf functions create errors whose content is a text message and whom can trace stack frames. Wrap and Wrapf create errors by wrapping an existing error with a similar error like New and Newf.

StackTrace tracing

Every error can track stack trace information. Just wrap it with errors.WithStack and a complete stack trace is captured.

err = errors.WithStack(err)

Printing the error results in a trace similar to:

some error: something happened:
    main.main
        /go-pogo/errors/.examples/3_with_kind/main.go:24
    main.doSomething
        /go-pogo/errors/.examples/3_with_kind/main.go:20
    main.someAction
        /go-pogo/errors/.examples/3_with_kind/main.go:16

Formatting

Wrap an existing error with errors.WithFormatter to upgrade the error to include basic formatting. Formatting is done using xerrors.FormatError and thus the same verbs are supported.

mt.Printf("%+v", errors.WithFormatter(err))

Catching panics

A convenient function is available to catch panics and store them as an error.

var err error
defer errors.CatchPanic(&err)

Backwards compatibility

Unwrap, Is, As are backwards compatible with the standard library's errors package and act the same.

Index

Constants

This section is empty.

Variables

View Source
var DefaultListCapacity uint = 8

Functions

func Append

func Append(dest *error, errs ...error)

Append appends multiple non-nil errors to a single multi error dest. When the value of dest is nil and errs only contains a single error, its value is set to the value of dest.

Important: when using Append with defer, the pointer to the dest error must be a named return variable. For additional details see https://golang.org/ref/spec#Defer_statements.

func AppendFunc added in v0.7.2

func AppendFunc(dest *error, fn func() error)

AppendFunc appends the non-nil error result of fn to dest using Append.

func As

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

As is an alias of errors.As. It finds the first error in err's chain that matches target, and if so, sets target to that error value and returns true.

func Callers added in v0.7.0

func Callers(skipFrames uint, dest *[]xerrors.Frame) int

Callers fills the stack *StackTrace with xerrors.Frame's from the point Callers is called, skipping the first skipFrames frames.

func CatchPanic added in v0.6.0

func CatchPanic(dest *error)

CatchPanic recovers from a panic and wraps it in an error. It then calls Append with the provided dest *error and wrapped panic. Use CatchPanic directly with defer. It is not possible to use CatchPanic inside a deferred function, like:

defer func(){ CatchPanic(&err }()

func Cause added in v0.7.0

func Cause(err error) error

Cause walks through all wrapped errors and returns the last error in the chain.

func Combine

func Combine(errors ...error) error

Combine returns a MultiError when more than one non-nil errors are provided. It returns a single error when only one error is passed, and nil if no non-nil errors are provided.

func FatalOnErr added in v0.7.2

func FatalOnErr(err error)

FatalOnErr prints the error to stderr and exits the program with an exit code that is not 0. When err is an ExitCoder its exit code is used.

func Filter

func Filter(errors []error) []error

Filter returns a slice of errors without nil values in between them. It returns the slice with the length of the amount of non-nil errors but keeps its original capacity.

func FormatError

func FormatError(err error, state fmt.State, verb rune)

FormatError calls the FormatError method of err with a xerrors.Printer configured according to state and verb, and writes the result to state. It will wrap err If err is not a xerrors.Formatter it will wrap err, so it is capable of basic error formatting using WithFormatter.

func GetExitCode

func GetExitCode(err error) int

GetExitCode returns an exit status code if the error implements the ExitCoder interface. If not, it returns 0.

func GetExitCodeOr added in v0.6.1

func GetExitCodeOr(err error, or int) int

GetExitCodeOr returns the exit status code from the first found ExitCoder in err's error chain. If none is found, it returns the provided value or.

func GetTime added in v0.7.0

func GetTime(err error) (time.Time, bool)

GetTime returns the time.Time of the last found Timer in err's error chain. If none is found, it returns the provided value or.

func Is

func Is(err, target error) bool

Is reports whether any error in err's chain matches target. It is fully compatible with both errors.Is and xerrors.Is.

An error is considered to match a target if it is equal to that target or if it implements a method Is(error) bool such that Is(target) returns true.

func Must

func Must(args ...interface{})

Must panics when any of the given args is a non-nil error. Its message is the error message of the first encountered error.

func New

func New(msg interface{}) error

New creates a new error which implements the StackTracer, Wrapper and xerrors.Formatter interfaces. Argument msg can be either a string or Msg.

err := errors.New("my error message")
err := errors.New(errors.Msg("my error message"))

New records a stack trace at the point it was called. Each call returns a distinct error value even if msg is identical. It will return nil if msg is nil. Use WithStack to wrap an existing error with a StackTracer and xerrors.Formatter.

func Newf

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

Newf formats an error message according to a format specifier and provided arguments with fmt.Errorf, and creates a new error similar to New.

err := errors.Newf("my error %s", "message")
err := errors.Newf("my error: %w", cause)

func Opaque

func Opaque(err error) error

Opaque is an alias of xerrors.Opaque. It returns an error with the same error formatting as err but that does not match err and cannot be unwrapped.

func PrintError

func PrintError(printer xerrors.Printer, err error)

PrintError prints the error err with the provided xerrors.Printer and additionally formats and prints the error's stack frames.

func Unembed added in v0.7.0

func Unembed(err error) error

Unembed recursively unwraps all Embedder errors and returns the (original) error that was wrapped with extra context. If err is not an Embedder, Unembed returns err as provided.

func Unwrap

func Unwrap(err error) error

Unwrap is an alias of errors.Unwrap. It returns the result of calling the Unwrap method on err, if err's type contains an Unwrap method returning error. Otherwise, Unwrap returns nil.

func UnwrapAll

func UnwrapAll(err error) []error

UnwrapAll returns the complete chain of errors, starting with the supplied error and ending with the root cause error.

func WithFormatter

func WithFormatter(err error) xerrors.Formatter

WithFormatter wraps the error with a xerrors.Formatter that is capable of basic error formatting. It returns the provided error as is if it already is a xerrors.Formatter, or nil when err is nil.

func WithKind

func WithKind(err error, kind Kind) error

WithKind wraps an error with Kind, therefore extending the error chain.

func Wrap

func Wrap(cause error, msg interface{}) error

Wrap creates a new error, which implements the StackTracer, Wrapper and xerrors.Formatter interfaces, that wraps around the causing error. Argument msg can be either a string or Msg.

err = errors.Wrap(err, "my error message")
err = errors.Wrap(err, errors.Msg("my error message"))

Wrap records a stack trace at the point it was called. Each call returns a distinct error value even if cause and msg are identical. Wrap will return nil when cause is nil, and it will return the provided cause when msg is nil.

func WrapPanic

func WrapPanic(prefix string)

WrapPanic wraps a panicking sequence with the given prefix. It then panics again.

func Wrapf

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

Wrapf formats an error message according to a format specifier and provided arguments with fmt.Errorf, and creates a new error similar to Wrap.

err = errors.Wrapf(err, "my error %s", "message")

Types

type Embedder added in v0.7.0

type Embedder interface {
	error
	Unembed() error
}

An Embedder unwraps an embedded error.

type ErrorLister

type ErrorLister interface {
	// ErrorList returns a List of collected non-nil errors.
	ErrorList() *List
}

type ExitCoder

type ExitCoder interface {
	error
	ExitCode() int
}

ExitCoder interfaces provide access to an exit code.

func WithExitCode

func WithExitCode(err error, exitCode int) ExitCoder

WithExitCode adds an exit status code to the error which may indicate a fatal error. The exit code can be supplied to os.Exit to terminate the program immediately.

type ExitCoderSetter added in v0.7.0

type ExitCoderSetter interface {
	ExitCoder
	SetExitCode(int)
}

type Kind

type Kind string

Kind describes the kind/type of error that has occurred. For example "auth error", "unmarshal error", etc. Errors can be of the same Kind but still contain different underlying causes. It is recommended to define each Kind as a constant.

const UnknownKind Kind = ""

UnknownKind is the default Kind for errors that are created without a distinct Kind.

func GetKind

func GetKind(err error) Kind

GetKind returns the Kind of the error if it is added with WithKind. If not, it returns UnknownKind.

func GetKindOr added in v0.6.1

func GetKindOr(err error, or Kind) Kind

GetKindOr returns the Kind of the error if it is added with WithKind. If not, it returns the provided Kind or.

func (Kind) As added in v0.7.0

func (k Kind) As(target interface{}) bool

func (Kind) Error added in v0.7.0

func (k Kind) Error() string

func (Kind) GoString added in v0.7.0

func (k Kind) GoString() string

func (Kind) Is added in v0.7.0

func (k Kind) Is(target error) bool

func (Kind) String

func (k Kind) String() string

String returns the string representation of Kind.

type List

type List struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

func NewList

func NewList(cap ...uint) *List

NewList creates a new List with a pre-allocated capacity of cap.

func (*List) All

func (l *List) All() []error

All returns the error slice within the list.

func (*List) Append

func (l *List) Append(err error) bool

Append an error to the list. It guarantees only non-nil errors are added. It returns false when a nil error is encountered. And true when the error is appended to the list.

func (*List) Combine

func (l *List) Combine() error

Combine the collected errors. It uses the same rules and logic as the Combine function.

func (*List) Empty added in v0.7.2

func (l *List) Empty() bool

Empty return true when the list is empty.

func (*List) Len

func (l *List) Len() int

Len returns the number of errors within the List.

func (*List) Prepend

func (l *List) Prepend(err error) bool

Prepend an error to the list. It guarantees only non-nil errors are added. It returns false when a nil error is encountered. And true when the error is prepended to the list.

type Msg added in v0.7.0

type Msg string

Msg is a string alias which can also be used as a basic error. This is particularly useful for defining constants of known errors in your library or application.

const ErrMyErrorMessage errors.Msg = "my error message"
const ErrAnotherError   errors.Msg = "just another error"

A new error can be constructed from any Msg with New and is considered to be equal when comparing with Is.

err := errors.New(ErrMyErrorMessage)
errors.Is(err, ErrMyErrorMessage) // true

func (Msg) As added in v0.7.0

func (m Msg) As(target interface{}) bool

func (Msg) Error added in v0.7.0

func (m Msg) Error() string

func (Msg) GoString added in v0.7.0

func (m Msg) GoString() string

func (Msg) Is added in v0.7.0

func (m Msg) Is(target error) bool

func (Msg) String added in v0.7.0

func (m Msg) String() string

type MultiError

type MultiError interface {
	error
	Errors() []error
}

type StackTrace added in v0.7.0

type StackTrace struct {

	// Skip n frames when formatting with Format, so overlapping frames from
	// previous errors are not printed.
	Skip uint
	// contains filtered or unexported fields
}

func GetStackTrace added in v0.7.0

func GetStackTrace(err error) *StackTrace

GetStackTrace returns a *StackTrace if err is a StackTracer or nil otherwise.

func (*StackTrace) Format added in v0.7.0

func (st *StackTrace) Format(printer xerrors.Printer)

Format formats the slice of xerrors.Frame using a xerrors.Printer.

func (*StackTrace) Frames added in v0.7.0

func (st *StackTrace) Frames() []xerrors.Frame

func (*StackTrace) Len added in v0.7.0

func (st *StackTrace) Len() uint

func (*StackTrace) String added in v0.7.0

func (st *StackTrace) String() string

type StackTracer

type StackTracer interface {
	error

	// StackTrace returns a stack of traces frames.
	StackTrace() *StackTrace
}

StackTracer interfaces provide access to a stack of traced StackTrace.

func WithStack added in v0.7.0

func WithStack(err error) StackTracer

WithStack gets a stack trace at the point WithStack was called and adds it to the error. If err is nil, WithStack returns nil.

type Timer added in v0.7.0

type Timer interface {
	error
	Time() time.Time
}

Timer interfaces provide access to a time.Time indicating when the error occurred.

func WithTime added in v0.7.0

func WithTime(err error, when time.Time) Timer

WithTime adds time information to the error. It does so by wrapping the error with a Timer, or update/set the time when error is a TimerSetter. It will return nil when the provided error is nil.

type TimerSetter added in v0.7.0

type TimerSetter interface {
	Timer
	SetTime(time.Time)
}

type UnsupportedTypeError added in v0.7.0

type UnsupportedTypeError struct {
	Func, Type string
}

func (*UnsupportedTypeError) Error added in v0.7.0

func (ut *UnsupportedTypeError) Error() string

type WaitGroup

type WaitGroup struct {
	// contains filtered or unexported fields
}

A WaitGroup is a collection of goroutines working on subtasks that are part of the same overall task. It collects possible errors returned from the subtasks and, unlike golang.org/x/sync/errgroup.Group, does not cancel the group when an error is encountered.

func (*WaitGroup) ErrorList

func (g *WaitGroup) ErrorList() *List

ErrorList returns a List of collected errors from the called goroutines.

func (*WaitGroup) Go

func (g *WaitGroup) Go(fn func() error)

Go calls the given function in a new goroutine. Errors from all calls are collected, combined and returned by Wait.

func (*WaitGroup) Wait

func (g *WaitGroup) Wait() error

Wait blocks until all function calls from the Go method have returned, then returns all collected errors as a combined (multi) error.

type Wrapper added in v0.7.0

type Wrapper interface {
	error
	xerrors.Wrapper
}

A Wrapper provides context around another error, which can be retrieved with Unwrap.

Jump to

Keyboard shortcuts

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