UNPKG

@alius/rpc

Version:

JSON-RPC 2.0 implementation configured with OpenRPC

96 lines (87 loc) 2.12 kB
"use strict"; import { Exception } from "@alius/exception"; /** * RPC Exception. * Class contains additional properties: code and data * * @extends Exception */ class RPCException extends Exception { /** @type {number} */ #code; #data; /** * Creates new RPC Exception instance with code, message and possible cause and data. * If provided code is not number then code -32603 (Internal error) is assigned. * * @param {number} [code=-32603] - error code * @param {string} [message="RPCError"] - message decribing exception * @param {Error|*} [cause=null] - initial cause for this error * @param {*} [data=null] - additional error data */ constructor(code, message, cause = null, data = null) { if (typeof code !== "number") { code = -32603; if (typeof message !== "string") { message = "Internal error"; } } if (typeof message !== "string") { message = "RPCError"; } super(message, cause); this.#code = code; this.#data = data; } /** * Returns error code. * * @type {number} * @readonly */ get code() { return this.#code; } /** * Returns additional error data. * * @type {*} * @readonly */ get data() { return this.#data; } /** * Returns object with serialized exception fields for JSON serialization * according to RPC specification. * Will have following properties:<ul> * <li>code - error code</li> * <li>message - error message</li> * <li>data - either data passed to constructor or * serialized this error without code and message properties</li> * </ul> * * @returns {JSONRPCErrorObject} */ toJSON() { const ret = { code: this.code, message: this.message, }; if (this.data) { ret.data = this.data; } else { const data = this.toObject(); // @ts-ignore delete data.code; // @ts-ignore delete data.message; ret.data = data; } return ret; } } export { RPCException }; /** * @typedef {import("./RPC").JSONRPCErrorObject} JSONRPCErrorObject */