| 35 | * Permits any integer error code. |
| 36 | */ |
| 37 | export class JsonRpcError<Data extends OptionalDataWithOptionalCause> extends Error { |
| 38 | // The `cause` definition can be removed when tsconfig lib and/or target have changed to >=es2022 |
| 39 | public cause?: unknown; |
| 40 | |
| 41 | public code: number; |
| 42 | |
| 43 | public data?: Data; |
| 44 | |
| 45 | constructor(code: number, message: string, data?: Data) { |
| 46 | if (!Number.isInteger(code)) { |
| 47 | throw new Error('"code" must be an integer.'); |
| 48 | } |
| 49 | |
| 50 | if (!message || typeof message !== "string") { |
| 51 | throw new Error('"message" must be a non-empty string.'); |
| 52 | } |
| 53 | |
| 54 | if (dataHasCause(data)) { |
| 55 | super(message, { cause: data.cause }); |
| 56 | |
| 57 | // Browser backwards-compatibility fallback |
| 58 | if (!Object.hasOwn(this, "cause")) { |
| 59 | Object.assign(this, { cause: data.cause }); |
| 60 | } |
| 61 | } else { |
| 62 | super(message); |
| 63 | } |
| 64 | |
| 65 | if (data !== undefined) { |
| 66 | this.data = data; |
| 67 | } |
| 68 | |
| 69 | this.code = code; |
| 70 | this.cause = (data as { cause?: unknown })?.cause; |
| 71 | } |
| 72 | |
| 73 | /** |
| 74 | * Get the error as JSON-serializable object. |
| 75 | * |
| 76 | * @returns A plain object with all public class properties. |
| 77 | */ |
| 78 | serialize(): SerializedJRPCError { |
| 79 | const serialized: SerializedJRPCError = { |
| 80 | code: this.code, |
| 81 | message: this.message, |
| 82 | }; |
| 83 | |
| 84 | if (this.data !== undefined) { |
| 85 | if (isPlainObject(this.data)) { |
| 86 | // Spread to avoid mutating `this.data` when setting `cause`. |
| 87 | serialized.data = { |
| 88 | ...(this.data as { [key: string]: Json }), |
| 89 | cause: serializeCause((this.data as { cause?: unknown }).cause), |
| 90 | }; |
| 91 | } else { |
| 92 | serialized.data = this.data as { [key: string]: Json }; |
| 93 | } |
| 94 | } |
nothing calls this directly
no outgoing calls
no test coverage detected