-
Notifications
You must be signed in to change notification settings - Fork 0
/
multi.go
79 lines (67 loc) · 1.66 KB
/
multi.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
// Package multi is an error type that holds multiple errors. These errors
// typically originate from operations that target multiple nodes.
// For example, a transaction proposal with two endorsers could return
// a multi error type if both endorsers return errors
package multi
import (
"fmt"
"strings"
)
// Errors is used to represent multiple errors
type Errors []error
// New Errors object with the given errors. Only non-nil errors are added.
func New(errs ...error) error {
errors := Errors{}
for _, err := range errs {
if err != nil {
errors = append(errors, err)
}
}
if len(errors) == 0 {
return nil
}
if len(errors) == 1 {
return errors[0]
}
return errors
}
// Append error to Errors. If the first arg is not an Errors object, one will be created
func Append(errs error, err error) error {
m, ok := errs.(Errors)
if !ok {
return New(errs, err)
}
if err == nil {
return errs
}
return append(m, err)
}
// ToError converts Errors to the error interface
// returns nil if no errors are present, a single error object if only one is present
func (errs Errors) ToError() error {
if len(errs) == 0 {
return nil
}
if len(errs) == 1 {
return errs[0]
}
return errs
}
// Error implements the error interface to return a string representation of Errors
func (errs Errors) Error() string {
if len(errs) == 0 {
return ""
}
if len(errs) == 1 {
return errs[0].Error()
}
errors := []string{fmt.Sprint("Multiple errors occurred:")}
for _, err := range errs {
errors = append(errors, err.Error())
}
return strings.Join(errors, " - ")
}