github.com/weaviate/weaviate@v1.24.6/entities/errorcompounder/compounder.go (about) 1 // _ _ 2 // __ _____ __ ___ ___ __ _| |_ ___ 3 // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \ 4 // \ V V / __/ (_| |\ V /| | (_| | || __/ 5 // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___| 6 // 7 // Copyright © 2016 - 2024 Weaviate B.V. All rights reserved. 8 // 9 // CONTACT: hello@weaviate.io 10 // 11 12 package errorcompounder 13 14 import ( 15 "fmt" 16 "strings" 17 18 "github.com/pkg/errors" 19 ) 20 21 type ErrorCompounder struct { 22 errors []error 23 } 24 25 func (ec *ErrorCompounder) Add(err error) { 26 if err != nil { 27 ec.errors = append(ec.errors, err) 28 } 29 } 30 31 func (ec *ErrorCompounder) Addf(msg string, args ...interface{}) { 32 ec.errors = append(ec.errors, fmt.Errorf(msg, args...)) 33 } 34 35 func (ec *ErrorCompounder) AddWrap(err error, wrapMsg ...string) { 36 if err != nil { 37 ec.errors = append(ec.errors, errors.Wrap(err, wrapMsg[0])) 38 } 39 } 40 41 func (ec *ErrorCompounder) ToError() error { 42 if len(ec.errors) == 0 { 43 return nil 44 } 45 46 var msg strings.Builder 47 for i, err := range ec.errors { 48 if i != 0 { 49 msg.WriteString(", ") 50 } 51 52 msg.WriteString(err.Error()) 53 } 54 55 return errors.New(msg.String()) 56 } 57 58 func (ec *ErrorCompounder) Len() int { 59 return len(ec.errors) 60 }