/errors

Go errors library

Primary LanguageGoMIT LicenseMIT

Errors

Go errors library.

Go Reference

Features

Message

New() creates an error with a message.

Wrap() adds a message to an error.

err := errors.New("error")
err = errors.Wrap(err, "message")
fmt.Println(err) // "message: error"

Stack trace

Errors created by New() and wrapped by Wrap() have a stack trace.

The error verbose message includes the stack trace.

errstack.Frames() returns the stack frames of the error.

frames := errors.StackFrames(err)

It's compatible with Sentry.

Verbose message

The error verbose message shows additional information about the error. Wrapping functions may provide a verbose message (stack, tag, value, etc.)

The Write()/String()/Formatter() functions write/return/format the error verbose message.

The first line is the error's message. The following lines are the verbose message of the error chain.

Example:

test: error
value c = d
tag a = b
temporary = true
ignored
stack
    github.com/pierrre/errors/integration_test_test.Test integration_test.go:17
    testing.tRunner testing.go:1576
    runtime.goexit asm_amd64.s:1598

Extend

Create a custom error type:

See the provided packages as example:

  • errbase: create a base error (e.g. sentinel error)
  • errmsg: add a message to an error
  • errstack: add a stack trace to an error
  • errtag: add a tag to an error
  • errval: add a value to an error
  • errignore: mark an error as ignored
  • errtmp: mark an error as temporary

Migrate from the std errors package

  • Replace the import errors with github.com/pierrre/errors
  • Replace fmt.Errorf("some wessage: %w", err) with errors.Wrap(err, "some message")
  • Use errbase.New() for sentinel error