-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherror.go
79 lines (68 loc) · 1.94 KB
/
error.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
// Package errorutil provides simple error wrapper for some features.
// Inspired by https://github.com/pkg/errors
//
// Currently, errorutil provides error chaining mechanism with hierachy, and auto stacktrace binding.
package errorutil
import (
"errors"
"fmt"
"io"
)
var _ error = (*wrapped)(nil)
var _ fmt.Formatter = (*wrapped)(nil)
// wrapped is wrapped error with extended features
type wrapped struct {
error
*causer
*traceable
}
// Is implements error interface. This makes error compare works properly.
func (w *wrapped) Is(err error) bool {
return errors.Is(w.error, err)
}
func (w *wrapped) Format(f fmt.State, verb rune) {
switch verb {
case 'v':
if f.Flag('+') {
_, _ = fmt.Fprintf(f, "%s (caused by: %v)", w.Error(), w.Cause())
return
}
fallthrough
case 's', 'q':
_, _ = io.WriteString(f, w.Error())
}
}
// Wrap wraps the error with provided options.
func Wrap(err error, opts ...WrapOpt) error {
if err == nil {
return nil
}
var we *wrapped
if errors.As(err, &we) && len(opts) == 0 {
// If error is already wrapped, and no additional options provided, just return it
return we
}
w := &wrapped{error: err}
for _, opt := range opts {
opt(w)
}
if w.traceable == nil {
// Auto bind stack trace if not already set
AutoStackTrace()(w)
}
return w
}
type WrapOpt func(w *wrapped)
// AutoStackTrace is the option which automatically bind caller's stacktrace to error. This makes some error-capturing module (like https://github.com/getsentry/sentry-go) can extract proper stacktrace of your error.
// For convenience, this option is enabled by default even if you don't include it.
func AutoStackTrace() WrapOpt {
return func(w *wrapped) {
w.traceable = traceableFromCallers(4)
}
}
// FromCause is the option which wraps the error with provided cause. If you Unwrap this error, provided cause will be extracted.
func FromCause(cause error) WrapOpt {
return func(w *wrapped) {
w.causer = &causer{cause: cause}
}
}