-
Notifications
You must be signed in to change notification settings - Fork 0
/
payload.go
87 lines (79 loc) · 1.66 KB
/
payload.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
package errors
import (
"encoding/json"
"net/http"
"strings"
)
type ErrPayload struct {
Code string
Desc string
HttpStatus int
Values map[string]interface{}
}
func (p *ErrPayload) MarshalJSON() ([]byte, error) {
m := make(map[string]interface{})
if p.Values != nil {
for k, v := range p.Values {
if k != httpStatusKey {
m[k] = v
}
}
}
m["errcode"] = p.Code
m["code"] = p.HttpStatus
if len(p.Desc) > 0 {
m["desc"] = p.Desc
}
m["type"] = strings.Split(p.Code, ".")[0]
return json.Marshal(m)
}
func (p *ErrPayload) UnmarshalJSON(data []byte) error {
m := make(map[string]interface{})
if err := json.Unmarshal(data, &m); err != nil {
return err
}
p.Code, _ = m["errcode"].(string)
delete(m, "errcode")
p.Desc, _ = m["desc"].(string)
delete(m, "desc")
p.HttpStatus, _ = m["code"].(int)
delete(m, "code")
p.Values = m
return nil
}
func NewErrPayload(err error) *ErrPayload {
var code, desc string
var httpStatus int
var values map[string]interface{}
switch err.(type) {
case *Err:
e := err.(*Err)
if e == nil {
code = OK
desc = ""
httpStatus = http.StatusOK
} else {
code = e.Code
desc = e.Error()
if desc == "<"+code+">" {
desc = ""
}
httpStatus = e.HttpStatus()
values = e.values
}
case nil:
code = OK
desc = ""
httpStatus = http.StatusOK
default:
code = TypeMismatch
desc = TypeMismatchError(err, "errors.*Err", "nil").Error()
httpStatus = http.StatusInternalServerError
}
return &ErrPayload{
Code: code,
Desc: desc,
HttpStatus: httpStatus,
Values: values,
}
}