Skip to content

Instantly share code, notes, and snippets.

@ijonas
Created September 19, 2016 21:39
Show Gist options
  • Save ijonas/0386c6e01c1479c9321e162be137d95c to your computer and use it in GitHub Desktop.
Save ijonas/0386c6e01c1479c9321e162be137d95c to your computer and use it in GitHub Desktop.
How to handle errors in #golang
Below are a bunch of resources that help you grok error handling in Go.
* Listen to Go Time Podcast #16, specifically the parts on error handling https://changelog.com/gotime-16/
* Read http://dave.cheney.net/2016/04/27/dont-just-check-errors-handle-them-gracefully
* Read http://dave.cheney.net/2016/06/12/stack-traces-and-the-errors-package
* Use the errors pkg for some syntactic sugar... https://godoc.org/github.com/pkg/errors
Use Dave Cheney's "rules"... either handle the error locally and then never again (e.g. log to stderr) OR
pass the error up the call stack. Consider annotating the error... errors.Wrapf(err, "Unable to access %s upload folder", account)
before passing it back up the stack.
Errors are really just values like ints and strings.
That penny dropped when I connected a "data producer" to a "data consumer" via a Go channel. The producer produces messages,
the consumer consumed them. But rather than just sending Messages over a channel, I started sending MessageAndError over the channel instead.
This meant the producer didn't have complicated error handling or fail drastically. If something went wrong during the
creation of the message, all I need to do was bundle the error with the message and sent it down the channel.
The MessageAndError consumer would decide what to do with each individual Message and Error. Reject the whole job, or after 50 errors, etc.
Good luck!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment