Tips for better error handling in go:
- Wrap the error being returned using
%w
andfmt.Errorf()
- Avoid words like
failed
orerror
- it is an error so we know something went wrong - Use present tense to describe what the code is trying to do
// good
fmt.Errorf("connecting to db: %w", err)
// bad
fmt.Errorf("could not connect to db: %w", err)
what makes Go’s error handling different is the opportunity it gives the programmer to tell a story. The trick to telling the story right is to add meaningful context to the error wherever possible. In Go, adding error context literally means expanding the message of the error you’ve just received with some explanatory text of what you were doing when the error occurred.
The error type in Go is a simple interface, exposing an Error() method returning a string. So, for practical reasons, all errors in Go can be equated to strings (although you can make them more complex if you want to).