Add rpc error fields (#4637)

* [WIP] Add RpcError

Currently located in rpc-core at request of maintainer. However unclear as to how it should be used, because the error
needs to be thrown in rpc-provider, and depending on it causes a dependency loop.

* Move `RpcError` to `rpc-provider`

Also add tests
This commit is contained in:
Noah Corona
2022-03-15 08:20:16 +02:00
committed by GitHub
parent 1db2136a3d
commit cccd512d70
4 changed files with 176 additions and 1 deletions
+64
View File
@@ -0,0 +1,64 @@
// Copyright 2017-2022 @polkadot/rpc-provider authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { isFunction } from '@polkadot/util/is/function';
import { RpcErrorInterface } from '../types';
const UNKNOWN = -99999;
function extend (that: RpcError, name: string, value?: string | number): void {
Object.defineProperty(that, name, {
configurable: true,
enumerable: false,
value
});
}
/**
* @name RpcError
* @summary Extension to the basic JS Error.
* @description
* The built-in JavaScript Error class is extended by adding a code to allow for Error categorization. In addition to the normal `stack`, `message`, the numeric `code` and `data` (any types) parameters are available on the object.
* @example
* <BR>
*
* ```javascript
* const { RpcError } from '@polkadot/util');
*
* throw new RpcError('some message', RpcError.CODES.METHOD_NOT_FOUND); // => error.code = -32601
* ```
*/
export default class RpcError extends Error implements RpcErrorInterface {
public code!: number;
public data?: number | string;
public override message!: string;
public override name!: string;
public override stack!: string;
public constructor (message = '', code: number = UNKNOWN, data?: number | string) {
super();
extend(this, 'message', String(message));
extend(this, 'name', this.constructor.name);
extend(this, 'data', data);
extend(this, 'code', code);
if (isFunction(Error.captureStackTrace)) {
Error.captureStackTrace(this, this.constructor);
} else {
extend(this, 'stack', (new Error(message)).stack);
}
}
public static CODES = {
ASSERT: -90009,
INVALID_JSONRPC: -99998,
METHOD_NOT_FOUND: -32601, // Rust client
UNKNOWN
};
}