-
Notifications
You must be signed in to change notification settings - Fork 0
/
error.go
63 lines (56 loc) · 1.27 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
package gopherpc
import "encoding/json"
type errorContext struct {
Code ErrCode `json:"code"`
Message string `json:"message"`
}
type errorResponse struct {
Jsonrpc string `json:"jsonrpc"`
Error *errorContext `json:"error"`
ID interface{} `json:"id"`
//
bytesRepresentation []byte `json:"-"`
stringRepresentation string `json:"-"`
}
func (this *errorResponse) Marshall() ([]byte, error) {
if this.bytesRepresentation == nil ||
len(this.bytesRepresentation) == 0 {
bts, err := json.Marshal(this)
if err != nil {
return nil, err
}
this.bytesRepresentation = bts
}
return this.bytesRepresentation, nil
}
func (this *errorResponse) String() (string, error) {
if this.stringRepresentation == "" {
_, err := this.Marshall()
if err != nil {
return "", err
}
this.stringRepresentation = string(this.bytesRepresentation)
}
return this.stringRepresentation, nil
}
func Error(code ErrCode, message string) IResponse {
this := &errorResponse{
Jsonrpc: "2.0",
Error: &errorContext{
Code: code,
Message: message,
},
ID: nil,
}
return this
}
func ParseError(bts []byte) (*errorResponse, error) {
var (
resp = new(errorResponse)
)
err := json.Unmarshal(bts, resp)
if err != nil {
return nil, err
}
return resp, nil
}