stackerrors

package
v0.0.0-...-947ddfb Latest Latest
Warning

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

Go to latest
Published: Dec 30, 2022 License: MPL-2.0 Imports: 4 Imported by: 0

README

Stackerrors

Implementation of errors with stacktraces where errors are generated. Compatible with go 1.13 errors package.

Usage

You can create new errors with:

err := stackerrors.New("error string")

There is an Errorf() equivalent as well:

err := stackerrors.Errorf("format %s", string)

If you have a previously existing error and would like to wrap that error with a context string, you can use the Wrap() or Wrapf() functions.

err := stackerrors.Wrap(prev_err, "context string")
// OR
err := stackerrors.Wrapf(prev_err, "format context %s", "string")

The Errorf() and Wrapf() can take all formatting options defined in the fmt package. If you want to retrieve the first error, you can RootCause() function.

The New(), Errorf(), Wrap(), and Wrapf() functions all capture a stacktrace when the error was created. You can print the stacktrace using the %+v formatting option.

func FuncName() {
        fmt.Printf("%+v", stackerrors.New("base error"))
        fmt.Println()
        err := stackerrors.New("first error")
        err = stackerrors.Wrap(err, "second error")
        err = stackerrors.Wrap(err, "third error")
        fmt.Printf("%+v", err)
}

Output:

base error
--- /file/path/to/program.go:<line number> (FuncName) ---

third error
--- /file/path/to/program.go:<line number> (FuncName) ---
second error
--- /file/path/to/program.go:<line number> (FuncName) ---
first error
--- /file/path/to/program.go:<line number> (FuncName) ---

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Errorf

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

Errorf is a convenience function mimics fmt.Errorf, but returns a contextError with a stack trace too.

func New

func New(ctx string) error

New creates a new error with a context and a stack trace. Returns a contextError pointer.

func RootCause

func RootCause(err error) error

RootCause returns the root error that caused the chain or errors to being with. It repeatedly tries to unwrap the error until it can no longer be unwrapped.

func Wrap

func Wrap(err error, context string) error

Wrap is a convenience function around Wrapf

func Wrapf

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

Wrapf takes in an error, a string with optional formatting options, and returns an error that wraps the input error. The returned error can be unwrapped using the errors.Unwrap() method.

Under the hood, Wrapf returns a ContextError that stores both the original error and the formatted string.

Types

This section is empty.

Jump to

Keyboard shortcuts

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