forked from go-ap/client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
errors.go
106 lines (92 loc) · 1.65 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
package client
import (
"fmt"
"io"
"strings"
vocab "github.com/mix/activitypub"
)
type err struct {
err error
msg string
i vocab.IRI
}
func (e err) annotate(err error) err {
e.err = err
return e
}
func (e err) iri(i vocab.IRI) err {
e.i = i
return e
}
func errf(msg string, p ...interface{}) err {
return err{
msg: fmt.Sprintf(msg, p...),
}
}
// Error returns the formatted error
func (e err) Error() string {
s := strings.Builder{}
s.WriteString(e.msg)
if e.i != "" {
s.WriteString(": ")
s.WriteString(e.i.String())
}
if e.err != nil {
s.WriteString(": ")
s.WriteString(e.err.Error())
}
return s.String()
}
func (e err) Unwrap() error {
return e.err
}
func (e err) Format(s fmt.State, verb rune) {
switch verb {
case 's', 'v':
io.WriteString(s, e.msg)
switch {
case s.Flag('+'):
if e.err == nil {
return
}
io.WriteString(s, ": ")
io.WriteString(s, fmt.Sprintf("%+s", e.err))
}
}
}
type logger struct {
ctx Ctx
infoFn func(string, ...interface{})
errorFn func(string, ...interface{})
ctxStr string
}
func (l logger) WithContext(ctx ...Ctx) logger {
ll := l
ll.ctx = Ctx{}
for k, v := range l.ctx {
ll.ctx[k] = v
}
for _, c := range ctx {
for k, v := range c {
ll.ctx[k] = v
}
}
var logStr = ""
for k, v := range ll.ctx {
logStr = logStr + k + " " + fmt.Sprintf("%+v", v) + " "
}
ll.ctxStr = strings.TrimSpace(logStr)
return ll
}
func (l logger) InfoFn(msg string, p ...interface{}) {
if l.ctxStr != "" {
msg = l.ctxStr + " " + msg
}
l.infoFn(msg, p)
}
func (l logger) ErrorFn(msg string, p ...interface{}) {
if l.ctxStr != "" {
msg = l.ctxStr + " " + msg
}
l.errorFn(msg, p)
}