-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathfield.go
71 lines (58 loc) · 1.56 KB
/
field.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
package failure
import (
"fmt"
"io"
)
type key int
const (
KeyCode key = iota + 1
KeyContext
KeyMessage
KeyCallStack
)
// WithCode creates a new Field with the provided code.
// Generally, New and Translate functions should be used instead of this function.
// This function is useful when you create your own error wrapper functions.
func WithCode[C Code](c C) Field {
return codeField{c}
}
type codeField struct {
code any
}
func (c codeField) SetErrorField(setter FieldSetter) {
setter.Set(KeyCode, c.code)
}
// Context represents additional contextual information associated with an error.
// It implements the Field interface.
type Context map[string]string
// SetErrorField implements the Field interface.
func (c Context) SetErrorField(setter FieldSetter) {
setter.Set(KeyContext, c)
}
// FormatError implements the ErrorFormatter interface.
func (c Context) FormatError(w ErrorWriter) {
first := true
_, _ = io.WriteString(w, "{")
for k, v := range c {
if !first {
_, _ = io.WriteString(w, ",")
}
first = false
_, _ = fmt.Fprintf(w, "%s=%s", k, v)
}
_, _ = io.WriteString(w, "}")
}
// Message represents a human-readable error message.
// It implements the Field interface.
type Message string
// SetErrorField implements the Field interface.
func (m Message) SetErrorField(setter FieldSetter) {
setter.Set(KeyMessage, m)
}
// Messagef creates a new Message with the provided format and arguments.
func Messagef(format string, a ...any) Message {
return Message(fmt.Sprintf(format, a...))
}
func (m Message) String() string {
return string(m)
}