-
Notifications
You must be signed in to change notification settings - Fork 0
/
error_source.go
80 lines (67 loc) · 1.97 KB
/
error_source.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
package errorsource
import (
"errors"
"github.com/famarks/grafarg-plugin-sdk-go/backend"
)
func New(err error, source backend.ErrorSource, status backend.Status) Error {
return Error{err: err, source: source, status: status}
}
// Error captures error source and implements the error interface
type Error struct {
source backend.ErrorSource
status backend.Status
err error
}
// Error implements the interface
func (r Error) Error() string {
return r.err.Error()
}
// Unwrap implements the interface
func (r Error) Unwrap() error {
return r.err
}
// Source provides the error source
func (r Error) Source() backend.ErrorSource {
return r.source
}
// PluginError will apply the source as plugin
func PluginError(err error, override bool) error {
return SourceError(backend.ErrorSourcePlugin, err, override)
}
// DownstreamError will apply the source as downstream
func DownstreamError(err error, override bool) error {
return SourceError(backend.ErrorSourceDownstream, err, override)
}
// SourceError returns an error with the source
// If source is already defined, it will return it, or you can override
func SourceError(source backend.ErrorSource, err error, override bool) Error {
var sourceError Error
if errors.As(err, &sourceError) && !override {
return sourceError // already has a source
}
return Error{
source: source,
err: err,
}
}
// Response returns an error DataResponse given status, source of the error and message.
func Response(err error) backend.DataResponse {
var e Error
if !errors.As(err, &e) {
// generic error, default to "plugin" error source
return backend.DataResponse{
Error: err,
ErrorSource: backend.ErrorSourcePlugin,
Status: backend.StatusUnknown,
}
}
return backend.DataResponse{
Error: err,
ErrorSource: e.source,
Status: e.status,
}
}
// FromStatus returns error source from status
func FromStatus(status backend.Status) backend.ErrorSource {
return backend.ErrorSourceFromHTTPStatus(int(status))
}