-
Notifications
You must be signed in to change notification settings - Fork 0
/
xerror.go
executable file
·104 lines (93 loc) · 1.78 KB
/
xerror.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package xerr
import (
"fmt"
"path/filepath"
"runtime"
"strings"
"github.com/jinares/gopkg/xtools"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type (
XError struct {
Code XCode `json:"code"`
Message string `json:"message"`
Where string `json:"where"`
}
)
func (se *XError) GRPCStatus() *status.Status {
return status.New(codes.Code(se.Code), se.Message)
}
func caller(calldepth int, short bool) string {
_, file, line, ok := runtime.Caller(calldepth + 1)
if !ok {
file = "???"
line = 0
} else if short {
file = filepath.Base(file)
}
return fmt.Sprintf("%s:%d", file, line)
}
/*
Error() string
*/
func (p *XError) Error() string {
return fmt.Sprintf("%d %s", (p.Code), p.Message)
}
/*
Error() string
*/
func (p *XError) String() string {
return fmt.Sprintf("%s %s", p.Error(), p.Where)
}
func String(err error) string {
if err == nil {
return ""
}
if val, isok := (err).(*XError); isok {
return val.String()
}
return err.Error()
}
func XErr(code XCode, msg string, where ...bool) *XError {
if len(where) > 0 && where[0] {
return &XError{
Code: code,
Message: msg,
Where: caller(1, true),
}
}
return &XError{
Code: code,
Message: msg,
}
}
func FromXErr(err error) *XError {
if err == nil {
return nil
}
if xe, isok := err.(*XError); isok {
return xe
}
rpcerr, isok := status.FromError(err)
if isok {
return &XError{Code: XCode(rpcerr.Code()), Message: rpcerr.Message()}
}
msg := err.Error()
index := strings.Index(msg, " ")
if index < 1 {
return &XError{
Code: Unknown,
Message: msg,
}
}
codestr := msg[0:index]
icode, isok := xtools.IntVal(codestr)
if isok == false {
return &XError{
Code: Unknown,
Message: msg,
}
}
return &XError{Code: XCode(icode), Message: msg[index:]}
}