43

What's the difference between these three functions from Go's standard packages:

Wrapf returns an error annotating err with a stack trace at the point Wrapf is called, and the format specifier. If err is nil, Wrapf returns nil.

Errorf formats according to a format specifier and returns the string as a value that satisfies error. Errorf also records the stack trace at the point it was called.

Errorf formats according to a format specifier and returns the string as a value that satisfies error.

If the format specifier includes a %w verb with an error operand, the returned error will implement an Unwrap method returning the operand. It is invalid to include more than one %w verb or to supply it with an operand that does not implement the error interface. The %w verb is otherwise a synonym for %v.

When one should be used instead of others?

0

4 Answers 4

75

First, a correction:

github.com/pkg/errors is not part of the standard library! The standard errors package has a much smaller API.

That said, github.com/pkg/errors is very popular, and was* maintained by some prominent Gophers. It is, however, largely (though not completely**) obsoleted by Go 1.13's extended error support.

Understanding the difference between those three functions requires a bit of a history lesson. (I go into a bit more detail on this history in this video.)

Prior to Go 1.13, there was no officially-recognized way to "wrap" errors. github.com/pkg/errors filled this gap with the Wrap and Wrapf methods. This allowed wrapping an error with additional context (including a stack trace), while retaining the original error in pristine form.

When Go 1.13 was in development, github.com/pkg/errors was used to influence the new API, but the final version differed slightly. Rather than Wrap and Wrapf methods, they decided to extend the fmt.Errorf method with a new %w verb, which would perform error wrapping for you.

This means that the following bits of code are roughly** equivalent:

    import "github.com/pkg/errors"

    /* snip */

    return errors.Wrapf(err, "bad things")
    // +build go1.13

    import "fmt"

    /* snip */
    return fmt.Errorf("bad things: %w", err)

When Go 1.13 came out, and the %w verb was added to fmt.Errorf, github.com/pkg/errors followed suit and added the same support, so now Wrapf is effectively obsolete.

So this brings us to the present day recommendations:

  1. If you want stack traces in your errors, use github.com/pkg/errors.Wrap to wrap errors.
  2. If you don't care about stack traces, use fmt.Errorf from the standard library.
  3. Never use errors.Errorf since it breaks error unwrapping (e.g. errors.Is).
  4. If you want to minimize your usage of github.com/pkg/errors, you can use errors.WithStack(fmt.Errorf(...))

*The github.com/pkg/errors package is no longer actively maintained. The repo has been archived, and is no longer accepting updates, but remains available for use.

**The standard library's error package still does not include stack traces, so github.com/pkg/errors is still popular for that.

3
  • 1
    It's not really looking for new maintainers. It was for a while, but then Dave decided just to archive it and allow forks. Commented Mar 18, 2022 at 16:12
  • 1
    One difference between Wrapf(err, "") and Errorf("%w", err) is that wrapf would return nil if err is nil, but errorf would return an error regardless.
    – nobody
    Commented Aug 12, 2022 at 14:48
  • @nobody: Very true! Good observation. Commented Aug 13, 2022 at 20:55
8

Just a small test to illustrate Flimzy's answer, here is a very short test:


func errorsWrapF() {
    wrap_err := errors.Wrapf(errors.New("a random error"), "wrapper")
    fmt.Printf("%+v\n", wrap_err)
}
/* would print:
a random error
main.errorsWrapF
        /home/tests/gosandbox/error/main.go:18
main.main
        /home/tests/gosandbox/error/main.go:11
runtime.main
        /usr/local/go/src/runtime/proc.go:204
runtime.goexit
        /usr/local/go/src/runtime/asm_amd64.s:1374
wrapper
main.errorsWrapF
        /home/tests/gosandbox/error/main.go:19
main.main
        /home/tests/gosandbox/error/main.go:11
runtime.main
        /usr/local/go/src/runtime/proc.go:204
runtime.goexit
        /usr/local/go/src/runtime/asm_amd64.s:1374
*/


func errorsErrorF() {
    err := errors.Errorf("a random error because of %w", errors.New("a random error"))
    fmt.Printf("%+v\n", err)
}
/* would print:
a random error because of a random error
main.errorsErrorF
        /home/tests/gosandbox/error/main.go:27
main.main
        /home/tests/gosandbox/error/main.go:10
runtime.main
        /usr/local/go/src/runtime/proc.go:204
runtime.goexit
        /usr/local/go/src/runtime/asm_amd64.s:1374
*/



func fmtErrorF() {
    err := fmt.Errorf("a random error because of %w", errors.New("a random error"))
    fmt.Printf("%+v\n", err)
}
/* would print:
a random error because of a random error
*/
1
2

The main differences are the following:

  • fmt.Errorf(): format an error message
  • errors.Errorf(): format an error message and include the stack trace.
  • errors.Wrapf(): format an error message and include the stack trace. Another error is embedded in the message.

Which to use depends entirely on what you're looking for.

fmt.Errorf() is in the standard library and gives you fairly basic control over the error message. This is often sufficient.

The errors.* functions are an additional dependency. They include a stack trace which can be fairly helpful in debugging.

errors.Wrapf() is convenient when you want to pass an error back and augment the error message with more information (eg: file.Open fails with permission denied, you may want to augment it with `opening file "foo" failed with: permission denied").

For more information, I suggest you read the very doc you pasted and try the examples included in the docs.

1
  • Wrapf predates fmt.Errorf's %w verb, (also implemented by errors.Errorf), and is now obsoleted, but retained for backward compatibility. Commented May 22, 2020 at 12:40
0

I have made gitlab.com/tozd/go/errors as a spiritual successor of deprecated github.com/pkg/errors which modernizes it to the newer Go error handling patterns. On of things improved is in fact improvement around those functions. In gitlab.com/tozd/go/errors:

  • errors.Errorf is exactly the same as fmt.Errorf, but it records a stack trace. It supports %w to wrap an error or multiple errors. By nature of string interpolation using %w, error messages from wrapped errors are included in the new error message. You can change where error messages appear and how they are combined, but they are always included in full.
  • errors.Wrap on the other hand is used when you want to replace one error with another. That means that you can fully control what the error message of the new (resulting) error is. The error message from the original error does not have to be included. This is useful when you want to replace some internal error with a more friendly external error (or one which you export from your package as a sentinel error). The internal error is still accessible through unwrapping and is recorded as "the cause" of the new error (similar to how it is done in Python).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.