-
Notifications
You must be signed in to change notification settings - Fork 3
/
errors.go
66 lines (55 loc) · 1.16 KB
/
errors.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
package errors
import (
"encoding/json"
errmicro "github.com/micro/go-micro/errors"
"github.com/prometheus/common/log"
"strings"
)
type Error struct {
Code int `json:"code"`
Status int `json:"status"`
Detail string `json:"detail"`
Internal string `json:"internal,omitempty"`
Content interface{} `json:"content,omitempty"`
}
func (e *Error) Error() string {
b, _ := json.Marshal(e)
return string(b)
}
func Parse(err string) *Error {
e := new(Error)
error := json.Unmarshal([]byte(err), e)
if error != nil {
e.Detail = err
}
return e
}
func ParseFromRPCError(err error) error {
if err == nil {
return nil
}
errtxt := err.Error()
merr := errmicro.Parse(errtxt)
errtxt = merr.Detail
if idx := strings.Index(errtxt, "{"); idx != -1 {
errtxt = errtxt[idx:]
}
return Parse(errtxt)
}
var Errors = map[int]*Error{}
func addError(err *Error) *Error {
e, ok := Errors[err.Code]
if ok {
log.Fatalf("duplate error code: %v, %v", e, err)
}
Errors[err.Code] = err
return err
}
//常用错误
func BadRequest(code int, detail string) error {
return addError(&Error{
Code:code,
Status:400,
Detail:detail,
})
}