-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode_error.go
More file actions
90 lines (77 loc) · 1.71 KB
/
code_error.go
File metadata and controls
90 lines (77 loc) · 1.71 KB
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
package structerror
import (
"encoding/json"
"fmt"
)
const (
// CodeUnknown is unknown error code
CodeUnknown = 1099
// StatusUnknown is unknown error code status
StatusUnknown = "Unknown"
)
// CodeErrorFactory is to generate new CodeError
type CodeErrorFactory struct {
codeMap map[int]string
}
// CodeError is error with code
type CodeError struct {
Code int
Status string
Msg string
Causes []error
}
// NewCodeErrorFactory impletment a CodeErrorFactory
func NewCodeErrorFactory(codeMap map[int]string) CodeErrorFactory {
return CodeErrorFactory{
codeMap: codeMap,
}
}
// NewError generate a new CodeError
func (f CodeErrorFactory) Error(code int, msg string, causes ...error) CodeError {
st, ok := f.codeMap[code]
if !ok {
st = StatusUnknown
}
return CodeError{
Code: code,
Status: st,
Msg: msg,
Causes: causes,
}
}
// Error impletment Error interface
func (ce CodeError) Error() string {
return fmt.Sprintf("%s:%s", ce.Status, ce.Msg)
}
// Code impletment Code interface
func (ce CodeError) ErrorCode() int {
return ce.Code
}
// JSON impletment StructError interface
func (ce CodeError) JSON() (string, error) {
d, e := json.Marshal(ce)
if e != nil {
return "", e
}
return string(d), nil
}
// MarshalJSON impletement json.Marshal interface
func (ce CodeError) MarshalJSON() ([]byte, error) {
type strCodeError struct {
Code int `json:"code"`
Status string `json:"status"`
Msg string `json:"msg"`
Causes []string `json:"causes"`
}
strCauses := []string{}
for _, e := range ce.Causes {
strCauses = append(strCauses, e.Error())
}
sj := strCodeError{
Code: ce.Code,
Status: ce.Status,
Msg: ce.Msg,
Causes: strCauses,
}
return json.Marshal(sj)
}