-
Notifications
You must be signed in to change notification settings - Fork 0
/
error.go
71 lines (58 loc) · 1.32 KB
/
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
package bc
import (
"errors"
"fmt"
)
type Error struct {
Status int `json:"status"`
Code int `json:"code"`
Message string `json:"message"`
Extra map[string]interface{} `json:"extra,omitempty"`
RequestID string `json:"request_id,omitempty"`
}
func (e *Error) Error() string {
s := fmt.Sprintf("[%d/%d] %s", e.Status, e.Code, e.Message)
for k, v := range e.Extra {
s += fmt.Sprintf(" %v=%v", k, v)
}
if e.RequestID != "" {
s += fmt.Sprintf(" id=%s", e.RequestID)
}
return s
}
func IsErrorCodes(err error, codes ...int) bool {
var e *Error
if errors.As(err, &e) {
for _, code := range codes {
if e.Code == code {
return true
}
}
}
return false
}
func createError(status, code int, message string) error {
return &Error{
Status: status,
Code: code,
Message: message,
}
}
// errWithRequestID wrap err with request id
type errWithRequestID struct {
err error
requestID string
}
func (e *errWithRequestID) Unwrap() error {
return e.err
}
func (e *errWithRequestID) Error() string {
return fmt.Sprintf("%v id=%s", e.err, e.requestID)
}
func WrapErrWithRequestID(err error, id string) error {
if e, ok := err.(*Error); ok {
e.RequestID = id
return e
}
return &errWithRequestID{err: err, requestID: id}
}