...

Source file src/github.com/go-errors/errors/join_unwrap_backward.go

Documentation: github.com/go-errors/errors

     1  //go:build !go1.20
     2  // +build !go1.20
     3  
     4  package errors
     5  
     6  // Disclaimer: functions Join and Unwrap are copied from the stdlib errors
     7  // package v1.21.0.
     8  
     9  // Join returns an error that wraps the given errors.
    10  // Any nil error values are discarded.
    11  // Join returns nil if every value in errs is nil.
    12  // The error formats as the concatenation of the strings obtained
    13  // by calling the Error method of each element of errs, with a newline
    14  // between each string.
    15  //
    16  // A non-nil error returned by Join implements the Unwrap() []error method.
    17  func Join(errs ...error) error {
    18  	n := 0
    19  	for _, err := range errs {
    20  		if err != nil {
    21  			n++
    22  		}
    23  	}
    24  	if n == 0 {
    25  		return nil
    26  	}
    27  	e := &joinError{
    28  		errs: make([]error, 0, n),
    29  	}
    30  	for _, err := range errs {
    31  		if err != nil {
    32  			e.errs = append(e.errs, err)
    33  		}
    34  	}
    35  	return e
    36  }
    37  
    38  type joinError struct {
    39  	errs []error
    40  }
    41  
    42  func (e *joinError) Error() string {
    43  	var b []byte
    44  	for i, err := range e.errs {
    45  		if i > 0 {
    46  			b = append(b, '\n')
    47  		}
    48  		b = append(b, err.Error()...)
    49  	}
    50  	return string(b)
    51  }
    52  
    53  func (e *joinError) Unwrap() []error {
    54  	return e.errs
    55  }
    56  
    57  // Unwrap returns the result of calling the Unwrap method on err, if err's
    58  // type contains an Unwrap method returning error.
    59  // Otherwise, Unwrap returns nil.
    60  //
    61  // Unwrap only calls a method of the form "Unwrap() error".
    62  // In particular Unwrap does not unwrap errors returned by [Join].
    63  func Unwrap(err error) error {
    64  	u, ok := err.(interface {
    65  		Unwrap() error
    66  	})
    67  	if !ok {
    68  		return nil
    69  	}
    70  	return u.Unwrap()
    71  }
    72  

View as plain text