Error handling basics
Error Types
We prefer the use of the CockroachDB errors library at github.com/cockroachdb/errors. This is a superset of Go's own errors and pkg/errors.
errors.New()
for errors with simple static stringserrors.Newf()
for formatted error stringserrors.AssertionFailedf()
for assertion / internal errors that reflect a likely implementation bug by the CRL team and should be louder than usualAdd context on return paths using
errors.Wrap()
/errors.Wrapf()
Add user-directed hints with errors.WithHint()
See the doc README on the errors package for more
When returning errors, consider the following to determine the best choice:
Is this a simple error that needs no extra information? If so,
errors.New
should suffice.Do the clients need to detect and handle this error? If so, you should use a custom type, and implement the
Error()
method.Are you propagating an error returned by a downstream function? If so, check the RFC on error handling
If the client needs to detect the error, and you have created a simple error using errors.New
, use a var for the error.
Bad | Good |
---|---|