gitee.com/sy_183/go-common@v1.0.5-0.20231205030221-958cfe129b47/errors/errors.go (about) 1 package errors 2 3 import ( 4 "fmt" 5 "strings" 6 ) 7 8 type ErrorGroup interface { 9 Errors() []error 10 } 11 12 type Errors []error 13 14 func (es Errors) Append(err error) Errors { 15 if err != nil { 16 return append(es, err) 17 } 18 return es 19 } 20 21 func (es Errors) Errors() []error { 22 return es 23 } 24 25 func (es Errors) Error() string { 26 if len(es) == 0 { 27 return "<nil>" 28 } 29 ess := make([]string, len(es)) 30 for i, err := range es { 31 s := fmt.Sprintf("%q", err) 32 if i == 0 { 33 s = "[" + s 34 } 35 if i == len(es)-1 { 36 s += "]" 37 } 38 ess[i] = s 39 } 40 return strings.Join(ess, ", ") 41 } 42 43 func (es Errors) ToError() error { 44 if len(es) == 0 { 45 return nil 46 } 47 return es 48 } 49 50 func MakeErrors(es ...error) error { 51 var err error 52 for _, e := range es { 53 err = Append(err, e) 54 } 55 return err 56 } 57 58 func Append(left error, right error) error { 59 switch { 60 case left == nil: 61 return right 62 case right == nil: 63 return left 64 } 65 66 if r, ok := right.(Errors); ok { 67 if l, ok := left.(Errors); ok { 68 return append(l, r...) 69 } 70 return append(Errors{left}, r...) 71 } else if l, ok := left.(Errors); ok { 72 return append(l, right) 73 } 74 return Errors{left, right} 75 } 76 77 type StringError string 78 79 func (s StringError) Error() string { 80 return string(s) 81 }