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 = {})=>{