github.com/status-im/status-go@v1.1.0/mobile/response.go (about) 1 package statusgo 2 3 import ( 4 "encoding/json" 5 6 "github.com/status-im/status-go/account" 7 "github.com/status-im/status-go/eth-node/keystore" 8 "github.com/status-im/status-go/transactions" 9 ) 10 11 const ( 12 codeUnknown int = iota 13 // special codes 14 codeFailedParseResponse 15 codeFailedParseParams 16 // account related codes 17 codeErrNoAccountSelected 18 codeErrInvalidTxSender 19 codeErrDecrypt 20 ) 21 22 var errToCodeMap = map[error]int{ 23 account.ErrNoAccountSelected: codeErrNoAccountSelected, 24 transactions.ErrInvalidTxSender: codeErrInvalidTxSender, 25 keystore.ErrDecrypt: codeErrDecrypt, 26 } 27 28 type jsonrpcSuccessfulResponse struct { 29 Result interface{} `json:"result"` 30 } 31 32 type jsonrpcErrorResponse struct { 33 Error jsonError `json:"error"` 34 } 35 36 type jsonError struct { 37 Code int `json:"code,omitempty"` 38 Message string `json:"message"` 39 } 40 41 func prepareJSONResponse(result interface{}, err error) string { 42 code := codeUnknown 43 if c, ok := errToCodeMap[err]; ok { 44 code = c 45 } 46 47 return prepareJSONResponseWithCode(result, err, code) 48 } 49 50 func prepareJSONResponseWithCode(result interface{}, err error, code int) string { 51 if err != nil { 52 errResponse := jsonrpcErrorResponse{ 53 Error: jsonError{Code: code, Message: err.Error()}, 54 } 55 response, _ := json.Marshal(&errResponse) 56 return string(response) 57 } 58 59 data, err := json.Marshal(jsonrpcSuccessfulResponse{result}) 60 if err != nil { 61 return prepareJSONResponseWithCode(nil, err, codeFailedParseResponse) 62 } 63 return string(data) 64 }