-
Notifications
You must be signed in to change notification settings - Fork 104
/
error_generic.go
59 lines (52 loc) · 1.52 KB
/
error_generic.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
package gocb
import (
"encoding/json"
)
// GenericError wraps errors that come from the SDK, and can be returned from any service.
// Errors returned when protostellar is used are of this type.
//
// # UNCOMMITTED
//
// This API is UNCOMMITTED and may change in the future.
type GenericError struct {
InnerError error `json:"-"`
Context map[string]interface{} `json:"context,omitempty"`
}
// MarshalJSON implements the Marshaler interface.
func (e GenericError) MarshalJSON() ([]byte, error) {
var innerError string
if e.InnerError != nil {
innerError = e.InnerError.Error()
}
return json.Marshal(struct {
InnerError string `json:"msg,omitempty"`
Context map[string]interface{} `json:"context,omitempty"`
}{
InnerError: innerError,
Context: e.Context,
})
}
// Error returns the string representation of a kv error.
func (e GenericError) Error() string {
errBytes, serErr := json.Marshal(struct {
InnerError error `json:"-"`
Context map[string]interface{} `json:"context,omitempty"`
}{
InnerError: e.InnerError,
Context: e.Context,
})
if serErr != nil {
logErrorf("failed to serialize error to json: %s", serErr.Error())
}
return e.InnerError.Error() + " | " + string(errBytes)
}
// Unwrap returns the underlying reason for the error
func (e GenericError) Unwrap() error {
return e.InnerError
}
func makeGenericError(baseErr error, context map[string]interface{}) *GenericError {
return &GenericError{
InnerError: baseErr,
Context: context,
}
}