Home > front end >  What difference between errors.Wrap and errors.WithMessage
What difference between errors.Wrap and errors.WithMessage

Time:01-20

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

CodePudding user response:

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.

CodePudding user response:

errors.Wrap(err, "message") is used to wrap an existing error err with an additional message "message". This allows you to add more context or information to an error that has already occurred, while still preserving the original error message.

errors.WithMessage(err, "message") is used to create a new error with a specific message "message". This can be useful when you want to create a new error with a specific message, rather than wrapping an existing error.

  •  Tags:  
  • go
  • Related