Golang Tips & Tricks #1 - errors

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)


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
Did you like the post?

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

You May Also Enjoy

Golang Tips & Tricks #4 - internal folders 25 Mar 2019

While developing a library, we create a directory structure to keep the code organized. However, some exported functions or struct should not be used by users of the library. The achieve that, call...
golang   tipstricks

Golang Tips & Tricks #3 - graceful shutdown 18 Mar 2019

In the microservices' world, one thing what's worth considering is a graceful shutdown. This is important to not lose data while shutting down a container. The container orchestrator like Kubernete...
golang   tipstricks

Golang Tips & Tricks #2 - interfaces 11 Mar 2019

When it comes to interfaces, a good practice is to create an interface where you'll use it. Creating interfaces in advanced is not recommended in Go. There are two exceptions: * you're creating ...
golang   tipstricks