errors

package module
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Jul 28, 2021 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.Trace and an additional stack frame is captured and stored within the error.

err = errors.Trace(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 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.

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

The Unwrap, Is and As functions work on errors that may wrap other errors. An error wraps another error if its type has the method

Unwrap() error

If e.Unwrap() returns a non-nil error w, then we say that e wraps w.

Unwrap unpacks wrapped errors. If its argument's type has an Unwrap method, it calls the method once. Otherwise, it returns nil.

A simple way to create wrapped errors is to call Wrap or Wrapf. Another options i to create an error with Newf and apply the %w verb to the error argument:

errors.Unwrap(errors.Newf("... %w ...", ..., err, ...))

returns err.

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

Index

Constants

This section is empty.

Variables

View Source
var DefaultListCapacity uint = 8
View Source
var MustPanicFormat = "errors.Must: %+v"

MustPanicFormat is the template string used by the `Must()` function to format its panic message.

Functions

func Append

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

Append appends multiple non-nil errors to a single multi error dest.

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

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.

The chain consists of err itself followed by the sequence of errors obtained by repeatedly calling Unwrap.

An error matches target if the error's concrete value is assignable to the value pointed to by target, or if the error has a method As(interface{}) bool such that As(target) returns true. In the latter case, the As method is responsible for setting target.

As will panic if target is not a non-nil pointer to either a type that implements error, or to any interface type. As returns false if err is nil.

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, eg `defer func(){ CatchPanic(&err }()`.

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 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 an xerrors.Printer configured according to state and verb, and writes the result to state. If err is not an xerrors.Formatter it will wrap the error with an UpgradedError that is capable of basic error formatting using WithFormatter.

func GetExitCode

func GetExitCode(err error) int

func Is

func Is(err, target error) bool

Is is an alias of errors.Is. It reports whether any error in err's chain matches target.

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(text string) error

New is an alias of errors.New. It returns an error that formats as the given text. Each call to New returns a distinct error value even if the text is identical.

func Newf

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

Newf formats an error message according to a format specifier and provided arguments and creates a new error the same way New does. It serves as an alternative to fmt.Errorf.

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 Original

func Original(err error) error

Original returns the Original error if err is an UpgradedError. Otherwise it will return the given error err.

func PrintError

func PrintError(printer xerrors.Printer, err error)

func RootCause

func RootCause(err error) error

RootCause walks through all wrapped errors and returns the last (upgraded) error in the chain, which is the root cause error. To get the original non-upgraded root cause error use

Original(RootCause(err))

func Trace

func Trace(err error) error

Trace adds stack trace context to the error by calling StackTracer.Trace on the error. If the error is not a StackTracer it is wrapped with an UpgradedError that implements this interface.

func TraceSkip

func TraceSkip(err error, skipFrames uint) error

TraceSkip adds stack trace context to the error just like Trace. Unlike Trace it passes the skipFrames argument to StackTracer.Trace.

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 (upgraded) root cause error.

func Upgrade

func Upgrade(parent error) error

Upgrade upgrades the given standard error by wrapping it with an UpgradedError that can record stack frames and has basic error formatting. The original parent error can always be retrieved by calling Original on the result of Upgrade. Thus

Original(Upgrade(err)) == err

equals true.

func WithFormatter

func WithFormatter(parent error) xerrors.Formatter

WithFormatter wraps the error with an UpgradedError that is capable of basic error formatting, but only if it is not already wrapped.

func Wrap

func Wrap(cause error, text string) error

Wrap creates a new error that wraps around the causing error, thus extending the error chain. It will only create a new error when the provided cause error is not nil, otherwise it will return 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, a ...interface{}) error

Wrapf formats an error message according to a format specifier and provided arguments and creates a new error the same way Wrap() does.

Types

type ErrorLister

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

type ExitCoder

type ExitCoder interface {
	error
	ExitCode() int
}

func WithExitCode

func WithExitCode(parent error, exitCode int) ExitCoder

type Frames

type Frames []xerrors.Frame

func GetStackFrames

func GetStackFrames(err error) *Frames

func (Frames) Format

func (fr Frames) Format(p xerrors.Printer)

Format formats the captured frames using a xerrors.Printer.

func (*Frames) String

func (fr *Frames) String() string

String formats the captured frames and returns its string representation.

type Kind

type Kind string

Kind describes the kind/type of error that has occurred. For example "auth error", "unmarshal error", etc. This way errors can be of the same Kind but still contain different error messages or additional fields. 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 implements the Kinder interface. If not, it returns UnknownKind.

func (Kind) String

func (k Kind) String() string

String returns the string representation of Kind.

type Kinder

type Kinder interface {
	error
	Kind() Kind
}

Kinder interfaces provide access to a Kind.

func WithKind

func WithKind(parent error, kind Kind) Kinder

WithKind adds Kind to the error.

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) 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 MultiError

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

type StackTracer

type StackTracer interface {
	error
	StackFrames() *Frames
	Trace(skipFrames uint)
}

StackTracer interfaces provide access to a stack of traced Frames.

type Unwrapper

type Unwrapper interface {
	error
	// Unwrap returns the next error in the error chain.
	// If there is no next error, Unwrap returns nil.
	Unwrap() (next error)
}

An Unwrapper unpacks a wrapped error.

type UpgradedError added in v0.6.0

type UpgradedError interface {
	error
	// Original returns the Original error that resides in the UpgradedError.
	Original() (original error)
}

An UpgradedError is capable of returning its original error.

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.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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