github.com/oam-dev/kubevela@v1.9.11/pkg/utils/errors/list.go (about) 1 /* 2 Copyright 2021 The KubeVela Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package errors 18 19 import ( 20 "fmt" 21 "strings" 22 ) 23 24 // ErrorList wraps a list of errors, it also fit for an Error interface 25 type ErrorList []error 26 27 // Error implement error interface 28 func (e ErrorList) Error() string { 29 if !e.HasError() { 30 // it reports an empty string if error is nil 31 return "" 32 } 33 errMessages := make([]string, len(e)) 34 for i, err := range e { 35 errMessages[i] = err.Error() 36 } 37 return fmt.Sprintf("Found %d errors. [(%s)]", len(e), strings.Join(errMessages, "), (")) 38 } 39 40 // HasError check if any error exists in list 41 func (e ErrorList) HasError() bool { 42 if e == nil { 43 return false 44 } 45 return len(e) > 0 46 } 47 48 // AggregateErrors aggregate errors into ErrorList and filter nil, if no error found, return nil 49 func AggregateErrors(errs []error) error { 50 var es ErrorList 51 for _, err := range errs { 52 if err != nil { 53 es = append(es, err) 54 } 55 } 56 if es.HasError() { 57 return es 58 } 59 return nil 60 }