Structured errors
A structured error provides contextual information that can be crucial in handling the errors before they reach the user of a program. This recipe shows how such errors can be used.
How to do it...
- Define a struct containing metadata that captures the error situation.
- Implement the
Error() string
method to make it anerror
. - If the error can wrap other errors, include an
error
or[]error
to store those. - Optionally, implement the
Is(error) bool
method to control how to compare this error. - Optionally, implement
Unwrap() error
orUnwrap() []error
to return wrapped errors.
How it works...
Any data type implementing the error
interface (containing only one method, Error() string
) can be used as an error. This means that you can create data structures containing detailed error information that can be later acted upon. So, if you need several data fields to describe an error, instead of building an elaborate string and returning it via...