forked from free/sql_exporter
/
errors.go
78 lines (67 loc) · 1.94 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
package errors
import (
"fmt"
)
// WithContext is an error associated with a logging context string (e.g. `job="foo", instance="bar"`). It is formatted
// as:
// fmt.Sprintf("[%s] %s", Context(), RawError())
type WithContext interface {
error
Context() string
RawError() string
}
// withContext implements WithContext.
type withContext struct {
context string
err string
}
// New creates a new WithContext.
func New(context, err string) WithContext {
return &withContext{context, err}
}
// Errorf formats according to a format specifier and returns a new WithContext.
func Errorf(context, format string, a ...interface{}) WithContext {
return &withContext{context, fmt.Sprintf(format, a...)}
}
// Wrap returns a WithContext wrapping err. If err is nil, it returns nil. If err is a WithContext, it is returned
// unchanged.
func Wrap(context string, err error) WithContext {
if err == nil {
return nil
}
if w, ok := err.(WithContext); ok {
return w
}
return &withContext{context, err.Error()}
}
// Wrapf returns a WithContext that prepends a formatted message to err.Error(). If err is nil, it returns nil. If err
// is a WithContext, the returned WithContext will have the message prepended but the same context as err (presumed to
// be more specific).
func Wrapf(context string, err error, format string, a ...interface{}) WithContext {
if err == nil {
return nil
}
prefix := format
if len(a) > 0 {
prefix = fmt.Sprintf(format, a...)
}
if w, ok := err.(WithContext); ok {
return &withContext{w.Context(), prefix + ": " + w.RawError()}
}
return &withContext{context, prefix + ": " + err.Error()}
}
// Error implements error.
func (w *withContext) Error() string {
if len(w.context) == 0 {
return w.err
}
return "[" + w.context + "] " + w.err
}
// Context implements WithContext.
func (w *withContext) Context() string {
return w.context
}
// RawError implements WithContext.
func (w *withContext) RawError() string {
return w.err
}