-
Notifications
You must be signed in to change notification settings - Fork 52
/
Copy pathexception.h
111 lines (86 loc) · 2.25 KB
/
exception.h
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
105
106
107
108
109
110
111
/**
* @file exception.h
* @author Krzysztof Okupski
* @date 29.10.2014
* @version 1.0
*
* Declaration of error class for the JSON-RPC wrapper.
*/
#ifndef BITCOIN_API_EXCEPTION_H
#define BITCOIN_API_EXCEPTION_H
#include <string>
#include <sstream>
#include <iostream>
#include <json/json.h>
#include <json/reader.h>
#include <json/value.h>
#include <jsonrpccpp/client.h>
using Json::Value;
using Json::Reader;
using jsonrpc::Errors;
class BitcoinException: public std::exception
{
private:
int code;
std::string msg;
public:
explicit BitcoinException(int errcode, const std::string& message) {
/* Connection error */
if(errcode == Errors::ERROR_CLIENT_CONNECTOR){
this->code = errcode;
this->msg = removePrefix(message, " -> ");
/* Authentication error */
}else if(errcode == Errors::ERROR_RPC_INTERNAL_ERROR && message.size() == 18){
this->code = errcode;
this->msg = "Failed to authenticate successfully";
/* Miscellaneous error */
}else{
this->code = parseCode(message);
this->msg = parseMessage(message);
}
}
~BitcoinException() throw() { };
int getCode(){
return code;
}
std::string getMessage(){
return msg;
}
std::string removePrefix(const std::string& in, const std::string& pattern){
std::string ret = in;
unsigned int pos = ret.find(pattern);
if(pos <= ret.size()){
ret.erase(0, pos+pattern.size());
}
return ret;
}
/* Auxiliary JSON parsing */
int parseCode(const std::string& in){
Value root;
Reader reader;
/* Remove JSON prefix */
std::string strJson = removePrefix(in, "INTERNAL_ERROR: : ");
int ret = -1;
/* Parse error message */
bool parsingSuccessful = reader.parse(strJson.c_str(), root);
if(parsingSuccessful) {
ret = root["error"]["code"].asInt();
}
return ret;
}
std::string parseMessage(const std::string& in){
Value root;
Reader reader;
/* Remove JSON prefix */
std::string strJson = removePrefix(in, "INTERNAL_ERROR: : ");
std::string ret = "Error during parsing of >>" + strJson + "<<";
/* Parse error message */
bool parsingSuccessful = reader.parse(strJson.c_str(), root);
if(parsingSuccessful) {
ret = removePrefix(root["error"]["message"].asString(), "Error: ");
ret[0] = toupper(ret[0]);
}
return ret;
}
};
#endif