From 1d48a835d880771eacf619fc9f8eb3ca09e19ef5 Mon Sep 17 00:00:00 2001 From: sadaf Date: Sun, 25 Feb 2024 23:43:01 +0530 Subject: [PATCH] feat: throwing more descriptive errors --- src/errors.ts | 26 ++++++++++++++++++++++++++ src/ws/websocket.ts | 37 +++++++++++++++++++++---------------- 2 files changed, 47 insertions(+), 16 deletions(-) create mode 100644 src/errors.ts diff --git a/src/errors.ts b/src/errors.ts new file mode 100644 index 0000000..0508653 --- /dev/null +++ b/src/errors.ts @@ -0,0 +1,26 @@ +export class NeutralinoError extends Error { + code: string; + message: string; + + constructor({ + code, + message + }: { + code: string; + message: string; + }) { + super(); + this.code = code; + this.message = message; + } +} + +export function logError(e) { + const error = JSON.stringify(e); + const errorObj = JSON.parse(error); + if (errorObj && typeof errorObj === 'object' && 'code' in errorObj && 'message' in errorObj) { + throw new NeutralinoError({ code: errorObj.code, message: errorObj.message}); + } else { + console.error('Invalid error object:', errorObj); + } +} diff --git a/src/ws/websocket.ts b/src/ws/websocket.ts index ed72503..4cf6da6 100644 --- a/src/ws/websocket.ts +++ b/src/ws/websocket.ts @@ -1,5 +1,6 @@ import * as extensions from '../api/extensions'; import * as events from '../browser/events'; +import { logError } from '../errors'; import { base64ToBytesArray } from '../helpers'; let ws; @@ -15,27 +16,31 @@ export function init() { registerSocketEvents(); } -export function sendMessage(method: string, data?: any): Promise { - return new Promise((resolve: any, reject: any) => { +export async function sendMessage(method: string, data?: any): Promise { + try { + return await new Promise((resolve: any, reject: any) => { - if(ws?.readyState != WebSocket.OPEN) { - sendWhenReady({method, data, resolve, reject}); - return; - } + if(ws?.readyState != WebSocket.OPEN) { + sendWhenReady({method, data, resolve, reject}); + return; + } - const id: string = uuidv4(); - const accessToken: string = getAuthToken(); + const id: string = uuidv4(); + const accessToken: string = getAuthToken(); - nativeCalls[id] = {resolve, reject}; + nativeCalls[id] = {resolve, reject}; - ws.send(JSON.stringify({ - id, - method, - data, - accessToken - })); + ws.send(JSON.stringify({ + id, + method, + data, + accessToken + })); - }); + }); + } catch (e) { + logError(e); + } } export function sendWhenReady(message: any) {