github.com/shuguocloud/go-zero@v1.3.0/core/errorx/batcherror.go (about)

     1  package errorx
     2  
     3  import "bytes"
     4  
     5  type (
     6  	// A BatchError is an error that can hold multiple errors.
     7  	BatchError struct {
     8  		errs errorArray
     9  	}
    10  
    11  	errorArray []error
    12  )
    13  
    14  // Add adds err to be.
    15  func (be *BatchError) Add(err error) {
    16  	if err != nil {
    17  		be.errs = append(be.errs, err)
    18  	}
    19  }
    20  
    21  // Err returns an error that represents all errors.
    22  func (be *BatchError) Err() error {
    23  	switch len(be.errs) {
    24  	case 0:
    25  		return nil
    26  	case 1:
    27  		return be.errs[0]
    28  	default:
    29  		return be.errs
    30  	}
    31  }
    32  
    33  // NotNil checks if any error inside.
    34  func (be *BatchError) NotNil() bool {
    35  	return len(be.errs) > 0
    36  }
    37  
    38  // Error returns a string that represents inside errors.
    39  func (ea errorArray) Error() string {
    40  	var buf bytes.Buffer
    41  
    42  	for i := range ea {
    43  		if i > 0 {
    44  			buf.WriteByte('\n')
    45  		}
    46  		buf.WriteString(ea[i].Error())
    47  	}
    48  
    49  	return buf.String()
    50  }