-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjson_marshal.go
44 lines (39 loc) · 946 Bytes
/
json_marshal.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
package errors
import (
"encoding/json"
)
type jsonError struct {
Code Kind `json:"code"`
Msg string `json:"message,omitempty"`
Cause string `json:"cause,omitempty"`
}
// MarshalJSON converts the err object to the JSON representation
func (e *Error) MarshalJSON() ([]byte, error) {
var err jsonError
err.Code = e.kind
err.Msg = e.msg
if e.cause != nil {
err.Cause = e.Cause().Error()
}
return json.Marshal(err)
}
// UnmarshalJSON deserializes JSON back to Error struct
func (e *Error) UnmarshalJSON(data []byte) error {
var err jsonError
if err := json.Unmarshal(data, &err); err != nil {
return err
}
e.kind = err.Code
e.msg = err.Msg
if cause := err.Cause; cause != "" {
e.cause = Str(cause)
}
return nil
}
// MarshalJSON converts the err object to the JSON representation
func (e *stringerr) MarshalJSON() ([]byte, error) {
var err jsonError
err.Code = Internal
err.Msg = e.msg
return json.Marshal(err)
}