-
Notifications
You must be signed in to change notification settings - Fork 0
/
namespaceerror.go
89 lines (68 loc) · 1.48 KB
/
namespaceerror.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
package oops
import (
"encoding/json"
"fmt"
"strings"
"github.com/calebcase/oops/lines"
)
// NamespaceError prefixes errors with the given namespace.
type NamespaceError struct {
Name string
Err error
}
var (
_ error = &NamespaceError{}
_ unwrapper = &NamespaceError{}
)
func (ne *NamespaceError) Error() string {
if ne == nil || ne.Err == nil {
return ""
}
return ne.Name + ": " + ne.Err.Error()
}
func (ne *NamespaceError) Unwrap() error {
if ne == nil {
return nil
}
return ne.Err
}
// Format implements fmt.Format.
func (ne *NamespaceError) Format(f fmt.State, verb rune) {
if ne == nil || ne.Err == nil {
fmt.Fprintf(f, "<nil>")
return
}
flag := ""
if f.Flag(int('+')) {
flag = "+"
}
if flag == "" {
fmt.Fprintf(f, "%s: %"+string(verb), ne.Name, ne.Err)
return
}
output := []string{}
ls := lines.Sprintf("%"+flag+string(verb), ne.Err)
output = append(output, fmt.Sprintf("%s: %s", ne.Name, ls[0]))
if len(ls) > 1 {
output = append(output, ls[1:]...)
}
f.Write([]byte(strings.Join(output, "\n")))
}
// MarshalJSON implements json.Marshaler.
func (ne *NamespaceError) MarshalJSON() (bs []byte, err error) {
if ne == nil || ne.Err == nil {
return []byte("null"), nil
}
ebs, err := ErrorMarshalJSON(ne.Err)
if err != nil {
return nil, err
}
output := struct {
Type string `json:"type"`
Err json.RawMessage `json:"err"`
}{
Type: fmt.Sprintf("%T", ne.Err),
Err: json.RawMessage(ebs),
}
return json.Marshal(output)
}