Error tracing and annotation.

Related tags

Error Handling errgo


-- import ""

The errors package provides a way to create and diagnose errors. It is compatible with the usual Go error idioms but adds a way to wrap errors so that they record source location information while retaining a consistent way for code to inspect errors to find out particular problems.


func Any

func Any(error) bool

Any returns true. It can be used as an argument to Mask to allow any diagnosis to pass through to the wrapped error.

func Cause

func Cause(err error) error

Cause returns the cause of the given error. If err does not implement Causer or its Cause method returns nil, it returns err itself.

Cause is the usual way to diagnose errors that may have been wrapped by Mask or NoteMask.

func Details

func Details(err error) string

Details returns information about the stack of underlying errors wrapped by err, in the format:

[{filename:99: error one} {otherfile:55: cause of error one}]

The details are found by type-asserting the error to the Locationer, Causer and Wrapper interfaces. Details of the underlying stack are found by recursively calling Underlying when the underlying error implements Wrapper.

func Is

func Is(err error) func(error) bool

Is returns a function that returns whether the an error is equal to the given error. It is intended to be used as a "pass" argument to Mask and friends; for example:

return errors.Mask(err, errors.Is(http.ErrNoCookie))

would return an error with an http.ErrNoCookie cause only if that was err's diagnosis; otherwise the diagnosis would be itself.

func Mask

func Mask(underlying error, pass ...func(error) bool) error

Mask returns an Err that wraps the given underyling error. The error message is unchanged, but the error location records the caller of Mask.

If err is nil, Mask returns nil.

By default Mask conceals the cause of the wrapped error, but if pass(Cause(err)) returns true for any of the provided pass functions, the cause of the returned error will be Cause(err).

For example, the following code will return an error whose cause is the error from the os.Open call when (and only when) the file does not exist.

f, err := os.Open("non-existent-file")
if err != nil {
	return errors.Mask(err, os.IsNotExist)

In order to add context to returned errors, it is conventional to call Mask when returning any error received from elsewhere.

func MaskFunc

func MaskFunc(allow ...func(error) bool) func(error, ...func(error) bool) error

MaskFunc returns an equivalent of Mask that always allows the specified causes in addition to any causes specified when the returned function is called.

It is defined for convenience, for example when all calls to Mask in a given package wish to allow the same set of causes to be returned.

func New

func New(s string) error

New returns a new error with the given error message and no cause. It is a drop-in replacement for errors.New from the standard library.

func Newf

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

Newf returns a new error with the given printf-formatted error message and no cause.

func NoteMask

func NoteMask(underlying error, msg string, pass ...func(error) bool) error

NoteMask returns an Err that has the given underlying error, with the given message added as context, and allowing the cause of the underlying error to pass through into the result if allowed by the specific pass functions (see Mask for an explanation of the pass parameter).

func Notef

func Notef(underlying error, f string, a ...interface{}) error

Notef returns an Error that wraps the given underlying error and adds the given formatted context message. The returned error has no cause (use NoteMask or WithCausef to add a message while retaining a cause).

func WithCausef

func WithCausef(underlying, cause error, f string, a ...interface{}) error

WithCausef returns a new Error that wraps the given (possibly nil) underlying error and associates it with the given cause. The given formatted message context will also be added.

type Causer

type Causer interface {
	Cause() error

Causer is the type of an error that may provide an error cause for error diagnosis. Cause may return nil if there is no cause (for example because the cause has been masked).

type Err

type Err struct {
	// Message_ holds the text of the error message. It may be empty
	// if Underlying is set.
	Message_ string

	// Cause_ holds the cause of the error as returned
	// by the Cause method.
	Cause_ error

	// Underlying holds the underlying error, if any.
	Underlying_ error

	// Location holds the source code location where the error was
	// created.
	Location_ Location

Err holds a description of an error along with information about where the error was created.

It may be embedded in custom error types to add extra information that this errors package can understand.

func (*Err) Cause

func (e *Err) Cause() error

Cause implements Causer.

func (*Err) Error

func (e *Err) Error() string

Error implements error.Error.

func (*Err) GoString

func (e *Err) GoString() string

GoString returns the details of the receiving error message, so that printing an error with %#v will produce useful information.

func (*Err) Location

func (e *Err) Location() Location

Location implements Locationer.

func (*Err) Message

func (e *Err) Message() string

Message returns the top level error message.

func (*Err) SetLocation

func (e *Err) SetLocation(callDepth int)

Locate records the source location of the error by setting e.Location, at callDepth stack frames above the call.

func (*Err) Underlying

func (e *Err) Underlying() error

Underlying returns the underlying error if any.

type Location

type Location struct {
	File string
	Line int

Location describes a source code location.

func (Location) IsSet

func (loc Location) IsSet() bool

IsSet reports whether the location has been set.

func (Location) String

func (loc Location) String() string

String returns a location in filename.go:99 format.

type Locationer

type Locationer interface {
	Location() Location

Location can be implemented by any error type that wants to expose the source location of an error.

type Wrapper

type Wrapper interface {
	// Message returns the top level error message,
	// not including the message from the underlying
	// error.
	Message() string

	// Underlying returns the underlying error, or nil
	// if there is none.
	Underlying() error

Wrapper is the type of an error that wraps another error. It is exposed so that external types may implement it, but should in general not be used otherwise.

  • mask hides errors case by default

    mask hides errors case by default

    Hey there,

    we really like that library and use it in several projects. Currently I try to wrap my head around the original cause of an error. I noticed that one needs to do something like errgo.Mask(err, errgo.Any) to be able to do something like errgo.Cause(err), to find the original cause of a problem. I question myself why one ever would like to hide the cause of an err. Wouldn't it be nicer to track the cause of each error by default or provide something like MaskWithCause(error)? May someone could explain the intentions behind that behaviour or if I miss something obvious.

    All the best

    opened by xh3b4sd 6
  • How to get the original error?

    How to get the original error?

    Let's imagine the following scenario.

    type CustomError struct {}
    func (err *CustomError) Error() string { … }
    func a() error {
       return &CustomError{}
    func b() error {
       err := a()
       if err != nil {
         return errgo.Mask(err)
    func c() error {
       err := b()
       if err != nil {
         return errgo.Mask(err)
    func main() {
      err := c()
      if err != nil {
         // Here I want to check if the source of err is a CustomError, how can I do it ?

    The example speaks for itself I think, when several levels of masking are applied, when the error is returning to the "upper" level of the application (http request handler, or anything else), what is the proper way to track its origin?


    opened by Soulou 5
  • Fix two errors found by go vet

    Fix two errors found by go vet

    One major, one minor.

    errors.go:90: comparison of function Underlying == nil is always false errors_test.go:223: errgo.Location composite literal uses unkeyed fields

    opened by davecheney 2
  • Fix gccgo compatibility

    Fix gccgo compatibility

    Introduce a conditional constant to deal with the implementation differences between gc and gccgo.

    There is one test still to fix (down from 5)

    --- FAIL: TestMask (0.00 seconds) errors_test.go:231: unexpected details: want "[{/home/dfc/src/ } {/home/dfc/src/ foo}]"; got "[{} {foo}]"

    opened by davecheney 2
  • Add TopCause() function

    Add TopCause() function

    The TopCause(error) function is the same as Cause, with the exception that it ignores masking. This is to address issue #8 , to be able to get the topmost error even if errors have been passed through multiple errgo.Mask(err)

    opened by klauspost 1
  • Is errgo.Err.Error() looking at the wrong error?

    Is errgo.Err.Error() looking at the wrong error?

    I was looking through errgo in a lot more detail, and I think I have found a strangeness. It appears the the Underlying_ attribute of the Err structure is used as the linked list back pointer, and the Cause_ is the error that is really cared about.

    // Error implements error.Error.
    func (e *Err) Error() string {
        switch {
        case e.Message_ == "" && e.Underlying == nil:
            return "<no error>"
        case e.Message_ == "":
            return e.Underlying_.Error()
        case e.Underlying_ == nil:
            return e.Message_
        return fmt.Sprintf("%s: %v", e.Message_, e.Underlying_)

    so... shouldn't the Error() method be looking at Cause_ and not Underlying_ ?

    opened by howbazaar 1
  • errors: fix errors found by vet

    errors: fix errors found by vet

    This pull request was made with an automated tool.

    The suggested change fixes one or more problems discovered by "go vet".

    See for more details on the @functionary GitHub user.

    opened by functionary 0
Wraps the normal error and provides an error that is easy to use with net/http.

Go HTTP Error Wraps the normal error and provides an error that is easy to use with net/http. Install go get -u Usage

Yuto Watanabe 0 Dec 20, 2021
Go error library with error portability over the network

cockroachdb/errors: Go errors with network portability This library aims to be used as a drop-in replacement to and Go's standar

CockroachDB 1.5k Dec 29, 2022
Reduce debugging time while programming Go. Use static and stack-trace analysis to determine which func call causes the error.

Errlog: reduce debugging time while programming Introduction Use errlog to improve error logging and speed up debugging while you create amazing code

Martin Joly 412 Nov 18, 2022
Generic error handling with panic, recover, and defer.

Generic error handling with panic, recover, and defer.

Marcos César de Oliveira 21 Aug 25, 2022
Error interface wrappers for Google's errdetails protobuf types, because they're handy as heck and I want to use them more

Error interface wrappers for Google's errdetails protobuf types, because they're handy as heck and I want to use them more

Claudia Hardman 1 Nov 18, 2021
Simple, intuitive and effective error handling for Go

Error Handling with eluv-io/errors-go The package eluv-io/errors-go makes Go error handling simple, intuitive and effective. err := someFunctionThatCa

Eluvio 0 Jan 19, 2022
This structured Error package wraps errors with context and other info

RErr package This structured Error package wraps errors with context and other info. It can be used to enrich logging, for example with a structured l

Rohan Allison 0 Jan 21, 2022
Simple error handling primitives

errors Package errors provides simple error handling primitives. go get The traditional error handling idiom in Go is roughly ak

null 8k Dec 26, 2022
A drop-in replacement for Go errors, with some added sugar! Unwrap user-friendly messages, HTTP status code, easy wrapping with multiple error types.

Errors Errors package is a drop-in replacement of the built-in Go errors package with no external dependencies. It lets you create errors of 11 differ

Kamaleshwar 47 Dec 6, 2022
A comprehensive error handling library for Go

Highlights The errorx library provides error implementation and error-related utilities. Library features include (but are not limited to): Stack trac

Joom 922 Jan 6, 2023
A Go (golang) package for representing a list of errors as a single error.

go-multierror go-multierror is a package for Go that provides a mechanism for representing a list of error values as a single error. This allows a fun

HashiCorp 1.8k Jan 1, 2023
A flexible error support library for Go

errors Please see for info License Copyright (C) 2014 Space Monkey, Inc. Licensed under the Apache Li

Space Monkey Go 168 Nov 3, 2022
A powerful, custom error package for Go

custom-error-go A powerful, custom error package for Go Detailed explanation:

Abhinav Bhardwaj 12 Apr 19, 2022
Declarative error handling for Go.

ErrorFlow Declarative error handling for Go. Motivation Reading list: Don't defer Close() on writable files Error Handling — Problem Overview Proposal

Serhiy T 8 Mar 3, 2022
Go extract error codes

go-extract-error-codes Overview This library helps to extract possible error codes from configured go-restful applications quality level: PoC High Lev

AccelByte Inc 0 Nov 24, 2021
brief: a piece of error handling codelet

brief a piece of error handling codelet. this code only demonstrates how to hide sql.ErrNoRows to the caller. the Get() method defined in the pkg/proj

null 0 Oct 30, 2021
Just another error handling primitives for golang

errors Just another error handling primitives for golang Install go install[email protected] Usage New error and print error context Th

Longlone 5 Feb 19, 2022
ApolloError compliant error function for gqlgen

gqlgen-apollo-error ApolloError compliant error function for gqlgen Installation $ go get -u Quickstart Retu

Shingo Ichikawa 2 Sep 6, 2022
🥷 CError (Custom Error Handling)

?? CError (Custom Error Handling) Installation Via go packages: go get Usage Here is a sample CError uses: import ( "gi

Rıdvan ÖZTURAÇ 3 Sep 21, 2022