-
Notifications
You must be signed in to change notification settings - Fork 0
/
errors.go
107 lines (94 loc) · 2.6 KB
/
errors.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package base
import (
"fmt"
"github.com/pkg/errors"
)
// These two interfaces are not exported by errors, but they are part of its
// stable interface.
type stackTracer interface {
StackTrace() errors.StackTrace
}
type causer interface {
Cause() error
}
// categorizer allows obtaining a category from an error, if provided.
type categorizer interface {
// Category returns the canonical error category for an error.
Category() error
}
// withCategory is a wrapped error (the cause) with a category and a stack.
type withCategory struct {
cause error
category error
stack errors.StackTrace
}
var _ categorizer = &withCategory{}
var _ causer = &withCategory{}
var _ error = &withCategory{}
var _ stackTracer = &withCategory{}
// ErrorWithCategory is similar to errors.Wrap, but instead of creating a new
// error as the wrapping message, a sentinel error is provided as a category.
// This category can then be inspected with HasErrorCategory.
func ErrorWithCategory(category error, cause error) error {
if cause == nil {
return category
}
var stack errors.StackTrace
if originalStack, ok := cause.(stackTracer); ok {
stack = originalStack.StackTrace()
} else {
// The error message is not important, we just want the stack trace.
// We'll also skip the current stack frame because we want the caller's
// instead.
stack = errors.New("").(stackTracer).StackTrace()[1:]
}
return &withCategory{
cause: cause,
category: category,
stack: stack,
}
}
func (c *withCategory) Error() string {
return fmt.Sprintf("%v: %v", c.category, c.cause)
}
func (c *withCategory) Cause() error { return c.cause }
func (c *withCategory) Category() error { return c.category }
func (c *withCategory) StackTrace() errors.StackTrace { return c.stack }
// HasErrorCategory returns whether the provided error belongs to the provided
// category.
func HasErrorCategory(err error, category error) bool {
if err == category {
return true
}
for err != nil {
cat, ok := err.(categorizer)
if ok && cat.Category() == category {
return true
}
cause, ok := err.(causer)
if !ok {
break
}
err = cause.Cause()
}
return false
}
// UnwrapCauseFromErrorCategory finds an error with the specified category in
// the chain and returns its Cause(). Returns nil if no such error was found.
func UnwrapCauseFromErrorCategory(err error, category error) error {
for err != nil {
cat, catOk := err.(categorizer)
cause, causeOk := err.(causer)
if catOk && cat.Category() == category {
if !causeOk {
return nil
}
return cause.Cause()
}
if !causeOk {
break
}
err = cause.Cause()
}
return nil
}