github.com/lingyao2333/mo-zero@v1.4.1/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 errs to be, nil errors are ignored. 15 func (be *BatchError) Add(errs ...error) { 16 for _, err := range errs { 17 if err != nil { 18 be.errs = append(be.errs, err) 19 } 20 } 21 } 22 23 // Err returns an error that represents all errors. 24 func (be *BatchError) Err() error { 25 switch len(be.errs) { 26 case 0: 27 return nil 28 case 1: 29 return be.errs[0] 30 default: 31 return be.errs 32 } 33 } 34 35 // NotNil checks if any error inside. 36 func (be *BatchError) NotNil() bool { 37 return len(be.errs) > 0 38 } 39 40 // Error returns a string that represents inside errors. 41 func (ea errorArray) Error() string { 42 var buf bytes.Buffer 43 44 for i := range ea { 45 if i > 0 { 46 buf.WriteByte('\n') 47 } 48 buf.WriteString(ea[i].Error()) 49 } 50 51 return buf.String() 52 }