Golang Tips & Tricks #1

You should use the package github.com/pkg/errors instead of errors package for errors in your applications. The default package lacks a few things like:

  • stack trace
  • easy appending message to the error
  • and more

It helps with debugging a lot. Below you can find an example error message with the stack trace.

An important thing to remember is that you should wrap every error which is from any external library or your freshly created error you want to return.

l, err := net.Listen("tcp4", fmt.Sprintf("%s:%d", host, port))
if err != nil {
    return errors.Wrapf(err, "cannot start listening on port %d", port)
}

or…

return errors.Wrap(MyError{}, "could not handle the situation")

If you want to add an extra message to already wrapped error, use WithMessage() function.

golang   tipstricks
Published in: Golang

About the author

Hi! My name is Bartek. I'm a developer since 2011. I love to learn by sharing the knowledge. You can find me on Twitter or Linkedin. I'm a backend engineer at Brainly.

Recent posts

I want to help you become a developer

That's why I can let you know about new blogposts on your email

You can find me