github.com/mysteriumnetwork/node@v0.0.0-20240516044423-365054f76801/utils/error_collection.go (about) 1 /* 2 * Copyright (C) 2019 The "MysteriumNetwork/node" Authors. 3 * 4 * This program is free software: you can redistribute it and/or modify 5 * it under the terms of the GNU General Public License as published by 6 * the Free Software Foundation, either version 3 of the License, or 7 * (at your option) any later version. 8 * 9 * This program is distributed in the hope that it will be useful, 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 * GNU General Public License for more details. 13 * 14 * You should have received a copy of the GNU General Public License 15 * along with this program. If not, see <http://www.gnu.org/licenses/>. 16 */ 17 18 package utils 19 20 import ( 21 "fmt" 22 "strings" 23 24 "github.com/pkg/errors" 25 ) 26 27 // ErrorCollection knows how to combine multiple error strings 28 type ErrorCollection []error 29 30 // Add puts given error to collection 31 func (ec *ErrorCollection) Add(errors ...error) { 32 for _, err := range errors { 33 if err != nil { 34 *ec = append(*ec, err) 35 } 36 } 37 } 38 39 // String concatenates collection to single string 40 func (ec *ErrorCollection) String() string { 41 return ec.Stringf("ErrorCollection: %s", ", ") 42 } 43 44 // Stringf returns a string representation of the underlying errors with the given format 45 func (ec *ErrorCollection) Stringf(format, errorDelimiter string) string { 46 errorStrings := make([]string, 0) 47 for _, err := range *ec { 48 errorStrings = append(errorStrings, err.Error()) 49 } 50 51 return fmt.Sprintf(format, strings.Join(errorStrings, errorDelimiter)) 52 } 53 54 // Error converts collection to single error 55 func (ec *ErrorCollection) Error() error { 56 if len(*ec) == 0 { 57 return nil 58 } 59 return errors.New(ec.String()) 60 } 61 62 // Errorf converts collection to single error by wanted format 63 func (ec *ErrorCollection) Errorf(format, errorDelimiter string) error { 64 if len(*ec) == 0 { 65 return nil 66 } 67 return errors.New(ec.Stringf(format, errorDelimiter)) 68 }