github.com/alloyzeus/go-azfl@v0.0.0-20231220071816-9740126a2d07/errors/call.go (about) 1 package errors 2 3 import "strings" 4 5 type CallError interface { 6 error 7 CallError() CallError 8 } 9 10 func IsCallError(e error) bool { 11 _, ok := e.(CallError) 12 return ok 13 } 14 15 // CallErrorSet is an interface to combine multiple CallError instances into a 16 // single CallError. 17 // 18 // In some cases, it's prefered to have all call-related errors for a call 19 // a list. This way, the user could fix them all in one go. 20 type CallErrorSet interface { 21 CallError 22 ErrorSet 23 CallErrors() []CallError 24 } 25 26 // UnwrapCallErrorSet returns the contained CallError instances if err is 27 // indeed a CallErrorSet. 28 func UnwrapCallErrorSet(err error) []CallError { 29 if errSet := asCallErrorSet(err); errSet != nil { 30 return errSet.CallErrors() 31 } 32 return nil 33 } 34 35 // asCallErrorSet returrns err as CallErrorSet if err is indeed a CallErrorSet, 36 // otherwise it returrns nil. 37 func asCallErrorSet(err error) CallErrorSet { 38 e, _ := err.(CallErrorSet) 39 return e 40 } 41 42 // CallSet creates a compound error comprised of multiple instances of 43 // CallError. The resulting error is also a CallError. 44 func CallSet(callErrors ...CallError) CallErrorSet { 45 ours := make([]CallError, len(callErrors)) 46 copy(ours, callErrors) 47 return callErrorSet(ours) 48 } 49 50 type callErrorSet []CallError 51 52 var ( 53 _ error = callErrorSet{} 54 _ CallError = callErrorSet{} 55 _ callErrorSet = callErrorSet{} 56 _ ErrorSet = callErrorSet{} 57 ) 58 59 func (e callErrorSet) Error() string { 60 if len(e) > 0 { 61 errs := make([]string, 0, len(e)) 62 for _, ce := range e { 63 errs = append(errs, ce.Error()) 64 } 65 s := strings.Join(errs, ", ") 66 if s != "" { 67 return "call: " + s 68 } 69 } 70 return "call error" 71 } 72 73 func (e callErrorSet) CallErrors() []CallError { 74 if len(e) > 0 { 75 errs := make([]CallError, len(e)) 76 copy(errs, e) 77 return errs 78 } 79 return nil 80 } 81 82 func (e callErrorSet) Errors() []error { 83 if len(e) > 0 { 84 errs := make([]error, 0, len(e)) 85 for _, i := range e { 86 errs = append(errs, i) 87 } 88 return errs 89 } 90 return nil 91 } 92 93 func (e callErrorSet) CallError() CallError { return e }