Skip to content

Commit

Permalink
fix fatal jsonrpc error, error handling, add content-length
Browse files Browse the repository at this point in the history
  • Loading branch information
shamoon committed Nov 24, 2022
1 parent 165add7 commit c2af1fb
Showing 1 changed file with 10 additions and 9 deletions.
19 changes: 10 additions & 9 deletions src/utils/proxy/handlers/jsonrpc.js
Expand Up @@ -10,27 +10,27 @@ const logger = createLogger("jsonrpcProxyHandler");

export async function sendJsonRpcRequest(url, method, params, username, password) {
const headers = {
"content-type": "application/json",
"accept": "application/json"
"Content-Type": "application/json",
"Accept": "application/json"
}

if (username && password) {
const authorization = Buffer.from(`${username}:${password}`).toString("base64");
headers.authorization = `Basic ${authorization}`;
headers.Authorization = `Basic ${Buffer.from(`${username}:${password}`).toString("base64")}`;
}

const client = new JSONRPCClient(async (rpcRequest) => {
const body = JSON.stringify(rpcRequest);
headers['Content-Length'] = Buffer.byteLength(body);
const httpRequestParams = {
method: "POST",
headers,
body: JSON.stringify(rpcRequest)
body
};

// eslint-disable-next-line no-unused-vars
const [status, contentType, data] = await httpProxy(url, httpRequestParams);
const dataString = data.toString();
if (status === 200) {
const json = JSON.parse(dataString);
const json = JSON.parse(data.toString());

// in order to get access to the underlying error object in the JSON response
// you must set `result` equal to undefined
Expand All @@ -40,7 +40,7 @@ export async function sendJsonRpcRequest(url, method, params, username, password
return client.receive(json);
}

return Promise.reject(new Error(dataString));
return Promise.reject(data?.error ? data : new Error(data.toString()));
});

try {
Expand All @@ -49,6 +49,7 @@ export async function sendJsonRpcRequest(url, method, params, username, password
}
catch (e) {
if (e instanceof JSONRPCErrorException) {
logger.warn("Error calling JSONPRC endpoint: %s. %s", url, e.message);
return [200, "application/json", JSON.stringify({result: null, error: {code: e.code, message: e.message}})];
}

Expand All @@ -73,7 +74,7 @@ export default async function jsonrpcProxyHandler(req, res) {

// eslint-disable-next-line no-unused-vars
const [status, contentType, data] = await sendJsonRpcRequest(url, method, null, widget.username, widget.password);
res.status(status).end(data);
return res.status(status).end(data);
}
}

Expand Down

0 comments on commit c2af1fb

Please sign in to comment.