-
Notifications
You must be signed in to change notification settings - Fork 0
/
marshable_error.go
107 lines (91 loc) · 2.6 KB
/
marshable_error.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
107
package errkit
import (
"encoding"
"encoding/json"
"github.com/kanisterio/errkit/internal/stack"
)
type jsonError struct {
Message string `json:"message,omitempty"`
Function string `json:"function,omitempty"`
LineNumber int `json:"linenumber,omitempty"`
File string `json:"file,omitempty"`
Details ErrorDetails `json:"details,omitempty"`
Cause any `json:"cause,omitempty"`
}
// UnmarshalJSON return error unmarshaled into jsonError.
func (e *jsonError) UnmarshalJSON(source []byte) error {
var parsedError struct {
Message string `json:"message,omitempty"`
Function string `json:"function,omitempty"`
LineNumber int `json:"linenumber,omitempty"`
File string `json:"file,omitempty"`
Details ErrorDetails `json:"details,omitempty"`
Cause json.RawMessage `json:"cause,omitempty"`
}
err := json.Unmarshal(source, &parsedError)
if err != nil {
return err
}
e.Message = parsedError.Message
e.Function = parsedError.Function
e.File = parsedError.File
e.LineNumber = parsedError.LineNumber
e.Details = parsedError.Details
if parsedError.Cause == nil {
return nil
}
// Trying to parse as jsonError
var jsonErrorCause *jsonError
err = json.Unmarshal(parsedError.Cause, &jsonErrorCause)
if err == nil {
e.Cause = jsonErrorCause
return nil
}
// fallback to any
var cause any
err = json.Unmarshal(parsedError.Cause, &cause)
if err == nil {
e.Cause = cause
}
return err
}
// jsonMarshable attempts to produce a JSON representation of the given err.
// If the resulting string is empty, then the JSON encoding of the err.Error()
// string is returned or empty if the Error() string cannot be encoded.
func jsonMarshable(err error) any {
if err == nil {
return nil
}
switch err.(type) {
case json.Marshaler, encoding.TextMarshaler:
return err
default:
// Otherwise wrap the error with {"message":"…"}
return jsonError{Message: err.Error()}
}
}
func MarshalErrkitErrorToJSON(err *errkitError) ([]byte, error) {
if err == nil {
return nil, nil
}
function, file, line := stack.GetLocationFromStack(err.stack, err.callers)
result := jsonError{
Message: err.Message(),
Function: function,
LineNumber: line,
File: file,
Details: err.Details(),
}
if err.cause != nil {
if kerr, ok := err.cause.(*errkitError); ok {
causeJSON, err := MarshalErrkitErrorToJSON(kerr)
if err != nil {
return nil, err
}
result.Cause = json.RawMessage(causeJSON)
} else {
result.Cause = jsonMarshable(err.cause)
}
}
return json.Marshal(result)
}