Allow generic Data param at RpcError (#4665)

* Allow generic Data param at RpcError

* Ensure that unless `Data` is specified, the field can't be accessed
This commit is contained in:
MOZGIII
2022-03-18 16:33:14 +02:00
committed by GitHub
parent f83d23d0f6
commit b0e8a8512a
3 changed files with 14 additions and 6 deletions
@@ -56,6 +56,14 @@ describe('RpcError', (): void => {
new RpcError('test message', 1234, data).data
).toEqual(data);
});
it('sets the .data property to generic value', (): void => {
const data = { custom: 'value' } as const;
expect(
new RpcError('test message', 1234, data).data
).toEqual(data);
});
});
describe('stack traces', (): void => {
+4 -4
View File
@@ -7,7 +7,7 @@ import { RpcErrorInterface } from '../types';
const UNKNOWN = -99999;
function extend (that: RpcError, name: string, value?: string | number): void {
function extend<Data, K extends keyof RpcError<Data>> (that: RpcError<Data>, name: K, value?: RpcError<Data>[K]): void {
Object.defineProperty(that, name, {
configurable: true,
enumerable: false,
@@ -29,10 +29,10 @@ function extend (that: RpcError, name: string, value?: string | number): void {
* throw new RpcError('some message', RpcError.CODES.METHOD_NOT_FOUND); // => error.code = -32601
* ```
*/
export default class RpcError extends Error implements RpcErrorInterface {
export default class RpcError<Data = never> extends Error implements RpcErrorInterface<Data> {
public code!: number;
public data?: number | string;
public data?: Data;
public override message!: string;
@@ -40,7 +40,7 @@ export default class RpcError extends Error implements RpcErrorInterface {
public override stack!: string;
public constructor (message = '', code: number = UNKNOWN, data?: number | string) {
public constructor (message = '', code: number = UNKNOWN, data?: Data) {
super();
extend(this, 'message', String(message));
+2 -2
View File
@@ -17,9 +17,9 @@ export interface JsonRpcResponseBaseError {
message: string;
}
export interface RpcErrorInterface {
export interface RpcErrorInterface<Data> {
code: number;
data?: string | number;
data?: Data;
message: string;
stack: string;
}