Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What difference between errors.Wrap and errors.WithMessage

Tags:

go

github.com/pkg/errors

This is Wrap(err error, msg string) https://pkg.go.dev/github.com/pkg/errors#Wrap

This is WithMessage(err error, msg string) https://pkg.go.dev/github.com/pkg/errors#WithMessage

both of these functions implement the interface causer https://pkg.go.dev/github.com/pkg/errors#Cause

This code works with errors.WithMessage, although I thought I should use errors.Wrap for errors.Cause

func main() {
    err := errors.New("first")
    err1 := errors.WithMessage(err, "tmp")
    err2 := errors.WithMessage(err1, "tmp")
    err3 := errors.WithMessage(err2, "tmp")
    fmt.Printf("%s", errors.Cause(err3))
}

Output: first

like image 947
nakem Avatar asked Sep 26 '26 21:09

nakem


1 Answers

The difference is that Wrap includes a call stack. If you click on a function name in the Go documentation, it will take you to the source, and you can see that both these functions are quite short and simple, and there is only one difference; while WithMessage creates a new error with the given message and cause (the error you pass in), Wrap takes this error and wraps it again like so:

&withStack{
    err,
    callers(),
}

Here err is the new error it just created (exactly like what you'd get from WithMessage) and callers populates a call stack. This is indicated in the documentation (emphasis mine):

Wrap returns an error annotating err with a stack trace at the point Wrap is called

Which is not mentioned in WithMessage as it's not done by that function.

like image 109
Adrian Avatar answered Sep 28 '26 22:09

Adrian