Re-format jsonrpc errors (#2014)

This commit is contained in:
Jaco Greeff
2020-03-09 08:27:00 +01:00
committed by GitHub
parent eb17de0888
commit ca9f671553
2 changed files with 21 additions and 7 deletions
@@ -42,6 +42,12 @@ describe('decodeResponse', (): void => {
).toThrow(/123: test error/);
});
it('throws any error found, with data', (): void => {
expect(
(): any => coder.decodeResponse({ id: 1, jsonrpc: '2.0', error: { code: 123, data: 'Error("Some random error description")', message: 'test error' } } as JsonRpcResponse)
).toThrow(/123: test error: Some random error description/);
});
it('returns the result', (): void => {
expect(
coder.decodeResponse({ id: 1, jsonrpc: '2.0', result: 'some result' } as JsonRpcResponse)
+15 -7
View File
@@ -6,6 +6,20 @@ import { JsonRpcRequest, JsonRpcResponse, JsonRpcResponseBaseError } from '../ty
import { assert, isUndefined, isNumber, isString } from '@polkadot/util';
function formatErrorData (data?: string | number): string {
if (isUndefined(data)) {
return '';
}
const formatted = isString(data)
? data.replace('Error("', '').replace('")', '')
: JSON.stringify(data);
// We need some sort of cut-off here since these can be very large and
// very nested, pick a number and trim the result display to it
return `: ${formatted.substr(0, 35)}`;
}
/** @internal */
export default class RpcCoder {
#id = 0;
@@ -54,13 +68,7 @@ export default class RpcCoder {
if (error) {
const { code, data, message } = error;
// We need some sort of cut-off here since these can be very large and
// very nested, pick a number and trim the result display to it
const _data = isUndefined(data)
? ''
: `: ${isString(data) ? data : JSON.stringify(data)}`.substr(0, 35);
throw new Error(`${code}: ${message}${_data}`);
throw new Error(`${code}: ${message}${formatErrorData(data)}`);
}
}
}