-
Notifications
You must be signed in to change notification settings - Fork 244
/
response.go
64 lines (53 loc) · 1.45 KB
/
response.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
package statusgo
import (
"encoding/json"
"github.com/ethereum/go-ethereum/accounts/keystore"
"github.com/status-im/status-go/account"
"github.com/status-im/status-go/transactions"
)
const (
codeUnknown int = iota
// special codes
codeFailedParseResponse
codeFailedParseParams
// account related codes
codeErrNoAccountSelected
codeErrInvalidTxSender
codeErrDecrypt
)
var errToCodeMap = map[error]int{
account.ErrNoAccountSelected: codeErrNoAccountSelected,
transactions.ErrInvalidTxSender: codeErrInvalidTxSender,
keystore.ErrDecrypt: codeErrDecrypt,
}
type jsonrpcSuccessfulResponse struct {
Result interface{} `json:"result"`
}
type jsonrpcErrorResponse struct {
Error jsonError `json:"error"`
}
type jsonError struct {
Code int `json:"code,omitempty"`
Message string `json:"message"`
}
func prepareJSONResponse(result interface{}, err error) string {
code := codeUnknown
if c, ok := errToCodeMap[err]; ok {
code = c
}
return prepareJSONResponseWithCode(result, err, code)
}
func prepareJSONResponseWithCode(result interface{}, err error, code int) string {
if err != nil {
errResponse := jsonrpcErrorResponse{
Error: jsonError{Code: code, Message: err.Error()},
}
response, _ := json.Marshal(&errResponse)
return string(response)
}
data, err := json.Marshal(jsonrpcSuccessfulResponse{result})
if err != nil {
return prepareJSONResponseWithCode(nil, err, codeFailedParseResponse)
}
return string(data)
}