Skip to content

Commit

Permalink
Catch fetch error
Browse files Browse the repository at this point in the history
  • Loading branch information
timonson committed Aug 5, 2023
1 parent aec6614 commit fc93517
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 6 deletions.
22 changes: 19 additions & 3 deletions client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,25 @@ export function createFetchRequest(
async function fetchResponse(
request: Request,
): Promise<JsonValue | undefined> {
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 & {
Expand Down
20 changes: 17 additions & 3 deletions client/dist/mod.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {})=>{
Expand Down

0 comments on commit fc93517

Please sign in to comment.