Errors with a stack trace
A Go package providing errors with a stack trace.
- Based of
github.com/pkg/errorswith similar API, addressing many its open issues. In many cases it can be used as a drop-in replacement. At the same time compatible with
- Uses standard error wrapping (available since Go 1.13).
%wformat verb to both wrap and record a stack trace at the same time (if not already recorded).
errors.Etype to be used instead of standard
errorto annotate which functions return errors with a stack trace.
- Clearly defines what are differences and expected use cases for:
errors.Basefunction to create errors without a stack trace to be used as base errors for
- Differentiates between wrapping and recording a cause: only
errors.Wraprecords a cause, while other functions are error transformers, wrapping the original.
- Novice friendly formatting of a stack trace when error is formatted using
%+v: tells what is the order of the stack trace and what is the relation between wrapped errors.
- Makes sure a stack trace is not recorded multiple times unnecessarily.
- Errors implement
MarshalJSONand can be marshaled into JSON.
This is a Go package. You can add it to your project using
go get gitlab.com/tozd/go/errors
See full package documentation with examples on pkg.go.dev.
Why a new Go errors package?
github.com/pkg/errors package amazing. But the project is archived and not developed anymore, with many issues not addressed (primarily because many require some backward incompatible change). At the same time it has been made before Go 1.13 added official support for wrapping errors and it does not (and cannot, in backwards compatible way) fully embrace it. This package takes what is best from
github.com/pkg/errors, but breaks things a bit to address many of the open issues community has identified since then and to modernize it to today's Go.
What are main differences from
uintptrand not custom type
- All error-wrapping functions return errors which implement the standard
unwrapperinterface, but only
errors.Wraprecords a cause error and returns an error which implements the
- All error-wrapping functions wrap the error into only one new error.
- Errors formatted using
Stack trace (most recent call first):and
The above error was caused by the following error:to make it clearer how is the stack trace formatted and how are multiple errors related to each other.
errors.Wrapalways records the stack trace while other functions do not record if it is already present.
errors.Causerepeatedly unwraps the error until it finds one which implements the
causerinterface, and then return its cause.