From fc93517a6a2b22561cc08c3982de7891d6d49c8e Mon Sep 17 00:00:00 2001 From: timonson Date: Sat, 5 Aug 2023 23:40:51 +0200 Subject: [PATCH] Catch fetch error --- client/client.ts | 22 +++++++++++++++++++--- client/dist/mod.js | 20 +++++++++++++++++--- 2 files changed, 36 insertions(+), 6 deletions(-) diff --git a/client/client.ts b/client/client.ts index 6aea140..fae6a72 100644 --- a/client/client.ts +++ b/client/client.ts @@ -28,9 +28,25 @@ export function createFetchRequest( async function fetchResponse( request: Request, ): Promise { - const response = await fetch(request); - const text = await response.text(); - return text === "" ? undefined : JSON.parse(text); + try { + const response = await fetch(request); + if (!response.ok) { + throw new Error( + `Received HTTP status code ${response.status} (${response.statusText}).`, + ); + } + const text = await response.text(); + return text === "" ? undefined : JSON.parse(text); + } catch (error) { + return { + jsonrpc: "2.0", + error: { + code: 0, + message: error.message, + }, + id: null, + }; + } } type MakeRpcCallOrNotificationOptions = CreateRequestOptions & { diff --git a/client/dist/mod.js b/client/dist/mod.js index ed36d26..6859533 100644 --- a/client/dist/mod.js +++ b/client/dist/mod.js @@ -68,9 +68,23 @@ function createFetchRequest(resource, rpcRequestOrBatch, options = {}) { }); } async function fetchResponse(request) { - const response = await fetch(request); - const text = await response.text(); - return text === "" ? undefined : JSON.parse(text); + try { + const response = await fetch(request); + if (!response.ok) { + throw new Error(`Received HTTP status code ${response.status} (${response.statusText}).`); + } + const text = await response.text(); + return text === "" ? undefined : JSON.parse(text); + } catch (error) { + return { + jsonrpc: "2.0", + error: { + code: 0, + message: error.message + }, + id: null + }; + } } function makeRpcCall(resource) { return async (rpcRequestInput, options = {})=>{