Skip to content
go-fasterPublic

About

clear go error wrapping with caller

Topics

Resources

Stars

66 stars

Watchers

1 watching

Forks

Latest commit

 

History

129 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

errors Go Reference codecov

Fork of xerrors with explicit Wrap instead of %w.

Clear is better than clever.

go get github.com/go-faster/errors
errors.Wrap(err, "message")

Why

  • Using Wrap is the most explicit way to wrap errors
  • Wrapping with fmt.Errorf("foo: %w", err) is implicit, redundant and error-prone
  • Parsing "foo: %w" is implicit, redundant and slow
  • The pkg/errors and xerrors are not maintainted
  • The cockroachdb/errors is too big
  • The errors has no caller stack trace

Wrap on nil

Wrap(nil, "msg") returns a non-nil error, matching fmt.Errorf("msg: %w", err) with a nil err (and unlike pkg/errors, which returns nil). Wrap only after checking err != nil:

if err := do(); err != nil {
    return errors.Wrap(err, "do")
}
return nil

wrapnil

cmd/wrapnil finds the two ways this goes wrong:

return errors.Wrap(f.Close(), "close") // fails every time: the result is not checked

if v == nil {
    return errors.Wrap(err, "no value") // err is nil here: an error without a cause
}
go install github.com/go-faster/errors/cmd/wrapnil@latest
go vet -vettool=$(which wrapnil) ./...

Build it with the same Go toolchain that runs go vet. Errors that are known to be non-nil are not reported: constructors (New, Errorf, Wrap, Join), ctx.Err(), context.Cause, http.ListenAndServe, and functions of the same package whose every return is a non-nil error. For a check the analyzer can't follow, put //wrapnil:ignore on the line or the line above.

Don't need traces?

Call errors.DisableTrace or use build tag noerrtrace.

Additional features

Into

Generic type assertion for errors.

// Into finds the first error in err's chain that matches target type T, and if so, returns it.
//
// Into is type-safe alternative to As.
func Into[T error](err error) (val T, ok bool)
if pathError, ok := errors.Into[*os.PathError](err); ok {
    fmt.Println("Failed at path:", pathError.Path)
}

Must

Must is a generic helper, like template.Must, that wraps a call to a function returning (T, error) and panics if the error is non-nil.

func Must[T any](val T, err error) T

License

BSD-3-Clause, same as Go sources

About

clear go error wrapping with caller

Topics

Resources

Stars

66 stars

Watchers

1 watching

Forks

Releases

Used by

Contributors

Languages