- Notifications
You must be signed in to change notification settings - Fork 371
/
Copy patherrors_go_other.go
78 lines (69 loc) · 2.08 KB
/
errors_go_other.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
//go:build !go1.20
// +build !go1.20
package jwt
import (
"errors"
"fmt"
)
// Is implements checking for multiple errors using [errors.Is], since multiple
// error unwrapping is not possible in versions less than Go 1.20.
func (jejoinedError) Is(errerror) bool {
for_, e:=rangeje.errs {
iferrors.Is(e, err) {
returntrue
}
}
returnfalse
}
// wrappedErrors is a workaround for wrapping multiple errors in environments
// where Go 1.20 is not available. It basically uses the already implemented
// functionality of joinedError to handle multiple errors with supplies a
// custom error message that is identical to the one we produce in Go 1.20 using
// multiple %w directives.
typewrappedErrorsstruct {
msgstring
joinedError
}
// Error returns the stored error string
func (wewrappedErrors) Error() string {
returnwe.msg
}
// newError creates a new error message with a detailed error message. The
// message will be prefixed with the contents of the supplied error type.
// Additionally, more errors, that provide more context can be supplied which
// will be appended to the message. Since we cannot use of Go 1.20's possibility
// to include more than one %w formatting directive in [fmt.Errorf], we have to
// emulate that.
//
// For example,
//
// newError("no keyfunc was provided", ErrTokenUnverifiable)
//
// will produce the error string
//
// "token is unverifiable: no keyfunc was provided"
funcnewError(messagestring, errerror, more...error) error {
// We cannot wrap multiple errors here with %w, so we have to be a little
// bit creative. Basically, we are using %s instead of %w to produce the
// same error message and then throw the result into a custom error struct.
varformatstring
varargs []any
ifmessage!="" {
format="%s: %s"
args= []any{err, message}
} else {
format="%s"
args= []any{err}
}
errs:= []error{err}
for_, e:=rangemore {
format+=": %s"
args=append(args, e)
errs=append(errs, e)
}
err=&wrappedErrors{
msg: fmt.Sprintf(format, args...),
joinedError: joinedError{errs: errs},
}
returnerr
}