Wrapping structured errors
A structured error can be used to decorate another error with additional information by wrapping it. This recipe shows how to do that.
How to do it...
- Keep an error member variable (or a slice of errors) to store the root cause in the structure.
- Implement
Unwrap() error(orUnwrap() []error) method.
How it works...
You can wrap the root cause error in a structured error. This allows you to add structured contextual information about the error:
type ErrFile struct {
   Name string
   When string
   Err error
}
func (err ErrFile) Error() string {
   return fmt.Sprintf("%s: file %s, when %s", err.Err, err.Name, err.
   When)
}
func (err ErrFile) Unwrap() error { return err.Err }
func ReadConfigFile(name string) error {
  f, err:=os.Open(name)
  if err!=nil {
     return ErrFile {
    ...