-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshadow.go
113 lines (88 loc) · 2.05 KB
/
shadow.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
108
109
110
111
112
113
package oops
import (
"encoding/json"
"fmt"
"strings"
"github.com/calebcase/oops/lines"
)
// ShadowError is an error with a hidden error inside.
type ShadowError struct {
Hidden error `json:"hidden"`
Err error `json:"err"`
}
var (
_ error = &ShadowError{}
_ unwrapper = &ShadowError{}
)
func (se *ShadowError) Error() string {
return fmt.Sprintf("%v", se)
}
func (se *ShadowError) Unwrap() error {
if se == nil || se.Err == nil || se.Hidden == nil {
return nil
}
return se.Err
}
// Format implements fmt.Format.
func (se *ShadowError) Format(f fmt.State, verb rune) {
if se == nil || se.Err == nil || se.Hidden == nil {
fmt.Fprintf(f, "<nil>")
return
}
flag := ""
if f.Flag(int('+')) {
flag = "+"
}
if flag == "" {
fmt.Fprintf(f, "%"+string(verb), se.Err)
return
}
output := lines.Indent(lines.Sprintf("%"+flag+string(verb), se.Err), "··", 1)
hidden := lines.Indent(lines.Sprintf("%"+flag+string(verb), se.Hidden), "··", 1)
output = append(output, "··hidden: "+hidden[0])
if len(hidden) > 1 {
output = append(output, hidden[1:]...)
}
fmt.Fprintf(f, strings.Join(output, "\n"))
}
// MarshalJSON implements json.Marshaler.
func (se *ShadowError) MarshalJSON() (bs []byte, err error) {
if se == nil || se.Err == nil {
return []byte("null"), nil
}
ebs, err := ErrorMarshalJSON(se.Err)
if err != nil {
return nil, err
}
output := struct {
Type string `json:"type"`
Err json.RawMessage `json:"err"`
}{
Type: fmt.Sprintf("%T", se.Err),
Err: json.RawMessage(ebs),
}
return json.Marshal(output)
}
// Shadow hides internal errors with another error.
func Shadow(hidden, err error) error {
if hidden == nil || err == nil {
return nil
}
return &ShadowError{
Hidden: hidden,
Err: err,
}
}
// ShadowP replaces hidden with error.
func ShadowP(hidden *error, err error) {
if hidden == nil {
return
}
*hidden = Shadow(*hidden, err)
}
// ShadowF returns a function that shadows hidden in place.
func ShadowF(hidden *error, err error) func() {
return func() {
ShadowP(hidden, err)
}
}