fix RPC server to handle exceptions in requests and return them as son values

This commit is contained in:
blagoev 2017-10-01 12:24:23 +03:00
parent 6e016b3e69
commit 49f65cd4da
2 changed files with 40 additions and 2 deletions

View File

@ -212,6 +212,23 @@ function makeRequest(url, data) {
return JSON.parse(responseText); return JSON.parse(responseText);
} }
//returns an object from rpc serialized json value
function deserialize_json_value(value) {
let result = {};
for (let index = 0; index < value.keys.length; index++) {
var propName = value.keys[index];
var propValue = value.values[index];
if (propValue.type && propValue.type == 'dict') {
result[propName] = deserialize_json_value(propValue);
}
else {
result[propName] = propValue.value;
}
}
return result;
}
function sendRequest(command, data, host = sessionHost) { function sendRequest(command, data, host = sessionHost) {
if (!host) { if (!host) {
throw new Error('Must first create RPC session with a valid host'); throw new Error('Must first create RPC session with a valid host');
@ -226,9 +243,13 @@ function sendRequest(command, data, host = sessionHost) {
let error = response && response.error; let error = response && response.error;
// Remove the type prefix from the error message (e.g. "Error: "). // Remove the type prefix from the error message (e.g. "Error: ").
if (error) { if (error && error.replace) {
error = error.replace(/^[a-z]+: /i, ''); error = error.replace(/^[a-z]+: /i, '');
} }
else if (error.type && error.type == 'dict') {
let responseError = deserialize_json_value(error);
throw responseError;
}
throw new Error(error || `Invalid response for "${command}"`); throw new Error(error || `Invalid response for "${command}"`);
} }

View File

@ -360,8 +360,25 @@ json RPCServer::perform_request(std::string name, const json &args) {
assert(action); assert(action);
m_worker.add_task([=] { m_worker.add_task([=] {
return action(args); try {
return action(args);
}
catch (jsc::Exception ex) {
json exceptionAsJson = nullptr;
try {
exceptionAsJson = serialize_json_value(ex);
}
catch (...) {
exceptionAsJson = {{"error", "An exception occured while processing the request. Could not serialize the exception as JSON"}};
}
return (json){{"error", exceptionAsJson}};
}
catch (std::exception &exception) {
return (json){{"error", exception.what()}};
}
}); });
} }
try { try {