github.com/verrazzano/verrazzano@v1.7.0/cluster-operator/internal/errors/errors.go (about) 1 // Copyright (c) 2023, Oracle and/or its affiliates. 2 // Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. 3 4 package errors 5 6 import ( 7 "fmt" 8 "strings" 9 ) 10 11 // ErrorAggregator provides an interface for building composite error strings, separated by a delimiter. 12 // The aggregator implements the error interface, allowing it to be returned from error-returning functions. 13 type ErrorAggregator struct { 14 delim string 15 errors []error 16 } 17 18 func NewAggregator(delim string) *ErrorAggregator { 19 return &ErrorAggregator{ 20 delim: delim, 21 errors: []error{}, 22 } 23 } 24 25 // Error builds the aggregated error string. 26 func (e *ErrorAggregator) Error() string { 27 sb := strings.Builder{} 28 for i, err := range e.errors { 29 sb.WriteString(err.Error()) 30 if i != len(e.errors)-1 { 31 sb.WriteString(e.delim) 32 } 33 } 34 return sb.String() 35 } 36 37 // Add appends a new error to the aggregation. 38 func (e *ErrorAggregator) Add(err error) { 39 e.errors = append(e.errors, err) 40 } 41 42 // Addf is equivalent to Add(fmt.Errorf(...)). 43 func (e *ErrorAggregator) Addf(format string, args ...any) { 44 e.Add(fmt.Errorf(format, args...)) 45 } 46 47 // HasError returns true if any errors have been added to the aggregator. 48 func (e *ErrorAggregator) HasError() bool { 49 return len(e.errors) > 0 50 }