/
rpc_error.go
65 lines (51 loc) · 1.2 KB
/
rpc_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
package utils
import (
"encoding/hex"
"encoding/json"
"fmt"
"github.com/Conflux-Chain/go-conflux-sdk/utils/abiutil"
"github.com/pkg/errors"
rpcutils "github.com/openweb3/go-rpc-provider/utils"
)
type RpcError struct {
Code int `json:"code"`
Message string `json:"message"`
Data interface{} `json:"data,omitempty"`
}
func (e *RpcError) Error() string {
if e == nil {
return ""
}
return fmt.Sprintf("%v, data: %v", e.Message, e.Data)
}
// ToRpcError converts a error to JsonError
func ToRpcError(origin error) (*RpcError, error) {
if !rpcutils.IsRPCJSONError(origin) {
return nil, errors.New("not a rpc error")
}
j, err := json.Marshal(errors.Cause(origin))
if err != nil {
return nil, errors.WithStack(err)
}
rpcErr := &RpcError{}
if err = json.Unmarshal(j, rpcErr); err != nil {
return nil, errors.WithStack(err)
}
hexStr, ok := rpcErr.Data.(string)
if !ok {
return rpcErr, nil
}
if !Has0xPrefix(hexStr) {
return rpcErr, nil
}
hexBytes, err := hex.DecodeString(hexStr[2:])
if err != nil {
return rpcErr, nil
}
data, err := abiutil.DecodeErrData(hexBytes)
if err != nil {
return rpcErr, nil
}
rpcErr.Message += ": " + data
return rpcErr, nil
}