k8s.io/perf-tests/clusterloader2@v0.0.0-20240304094227-64bdb12da87e/pkg/errors/error_list.go (about) 1 /* 2 Copyright 2018 The Kubernetes 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 "bytes" 21 "sync" 22 ) 23 24 // ErrorList is a thread-safe error list. 25 type ErrorList struct { 26 lock sync.Mutex 27 errors []error 28 } 29 30 // NewErrorList creates new error list. 31 func NewErrorList(errors ...error) *ErrorList { 32 return &ErrorList{ 33 errors: errors, 34 } 35 } 36 37 // IsEmpty returns true if there is no error in the list. 38 func (e *ErrorList) IsEmpty() bool { 39 e.lock.Lock() 40 defer e.lock.Unlock() 41 return len(e.errors) == 0 42 } 43 44 // Append adds errors to the list 45 func (e *ErrorList) Append(errs ...error) { 46 e.lock.Lock() 47 defer e.lock.Unlock() 48 e.errors = append(e.errors, errs...) 49 } 50 51 // Concat concatenates error lists. 52 func (e *ErrorList) Concat(e2 *ErrorList) { 53 if e2 == nil { 54 return 55 } 56 e.lock.Lock() 57 defer e.lock.Unlock() 58 e.errors = append(e.errors, e2.errors...) 59 } 60 61 // String returns error list as a single string. 62 func (e *ErrorList) String() string { 63 e.lock.Lock() 64 defer e.lock.Unlock() 65 var b bytes.Buffer 66 b.WriteString("[") 67 for i := 0; i < len(e.errors); i++ { 68 b.WriteString(e.errors[i].Error()) 69 if i != len(e.errors)-1 { 70 b.WriteString("\n") 71 } 72 } 73 b.WriteString("]") 74 return b.String() 75 } 76 77 // Error returns string representation of ErrorList. 78 func (e *ErrorList) Error() string { 79 return e.String() 80 }