github.com/alloyzeus/go-azfl@v0.0.0-20231220071816-9740126a2d07/errors/wrap.go (about)

     1  package errors
     2  
     3  // Unwrappable is an error which holds inner error, which usually
     4  // provides the cause if this error.
     5  type Unwrappable interface {
     6  	error
     7  	Unwrap() error
     8  }
     9  
    10  // Wrap creates a new error by providing context message to another error.
    11  // It's recommended for the message to describe what the program did which
    12  // caused the error.
    13  //
    14  //     err := fetchData(...)
    15  //     if err != nil { return errors.Wrap("fetching data", err) }
    16  //
    17  func Wrap(contextMessage string, causeErr error) error {
    18  	return &errorWrap{contextMessage, causeErr}
    19  }
    20  
    21  var _ Unwrappable = &errorWrap{}
    22  
    23  type errorWrap struct {
    24  	msg string
    25  	err error
    26  }
    27  
    28  func (e *errorWrap) Error() string {
    29  	if e.msg != "" {
    30  		if e.err != nil {
    31  			return e.msg + ": " + e.err.Error()
    32  		}
    33  		return e.msg
    34  	}
    35  	if e.err != nil {
    36  		return e.err.Error()
    37  	}
    38  	return ""
    39  }
    40  
    41  func (e *errorWrap) Unwrap() error {
    42  	return e.err
    43  }