github.com/gopherjs/gopherjs@v1.19.0-beta1.0.20240506212314-27071a8796e4/compiler/errors.go (about) 1 package compiler 2 3 import ( 4 "errors" 5 "fmt" 6 ) 7 8 // ErrTooManyErrors is added to the ErrorList by the Trim method. 9 var ErrTooManyErrors = errors.New("too many errors") 10 11 // ErrorList wraps multiple errors as a single error. 12 type ErrorList []error 13 14 func (errs ErrorList) Error() string { 15 if len(errs) == 0 { 16 return "<no errors>" 17 } 18 return fmt.Sprintf("%s (and %d more errors)", errs[0].Error(), len(errs[1:])) 19 } 20 21 // ErrOrNil returns nil if ErrorList is empty, or the error otherwise. 22 func (errs ErrorList) ErrOrNil() error { 23 if len(errs) == 0 { 24 return nil 25 } 26 return errs 27 } 28 29 // Append an error to the list. 30 // 31 // If err is an instance of ErrorList, the lists are concatenated together, 32 // otherwise err is appended at the end of the list. If err is nil, the list is 33 // returned unmodified. 34 // 35 // err := DoStuff() 36 // errList := errList.Append(err) 37 func (errs ErrorList) Append(err error) ErrorList { 38 if err == nil { 39 return errs 40 } 41 if err, ok := err.(ErrorList); ok { 42 return append(errs, err...) 43 } 44 return append(errs, err) 45 } 46 47 // AppendDistinct is similar to Append, but doesn't append the error if it has 48 // the same message as the last error on the list. 49 func (errs ErrorList) AppendDistinct(err error) ErrorList { 50 if l := len(errs); l > 0 { 51 if prev := errs[l-1]; prev != nil && err.Error() == prev.Error() { 52 return errs // The new error is the same as the last one, skip it. 53 } 54 } 55 56 return errs.Append(err) 57 } 58 59 // Trim the error list if it has more than limit errors. If the list is trimmed, 60 // all extraneous errors are replaced with a single ErrTooManyErrors, making the 61 // returned ErrorList length of limit+1. 62 func (errs ErrorList) Trim(limit int) ErrorList { 63 if len(errs) <= limit { 64 return errs 65 } 66 67 return append(errs[:limit], ErrTooManyErrors) 68 }