Don’t just check errors, handle them gracefully
- There are three core strategies for error handling in Go.
- Sentinel errors return a specific value. In error type handling, you create a type that implements the error interface. Error types are better than sentinel errors because they capture more context about what went wrong.
- But both sentinel & error types error handling become part of your public API. And they create source code dependency between the caller and the package that implements the error interface. Both ate best avoided
- Best option to use is an opaque error strategy that requires the least coupling between code and caller. The caller only knows an error happened, but they can’t see inside the error.
- Consider using an error package with two main functions - ‘wrap’ to take an error & a message to produce a new error; the second is ‘cause’ which takes the possibly wrapped error and unwraps it to discover the original issue.
- Only handle an error once. Inspect the error value and make a decision. No decision means the error is not handled.
Full post here, 11 mins read