Skip to content

Commit

Permalink
fix: default generic error message being used in all failure scenarios (
Browse files Browse the repository at this point in the history
#114)

Signed-off-by: Ardalan Amini <[email protected]>
  • Loading branch information
ardalanamini authored Mar 8, 2023
1 parent c89090a commit 42f6fbe
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 15 deletions.
17 changes: 12 additions & 5 deletions src/api/API.browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,18 @@ export default abstract class API extends Base {
.then(async (r) => {
clearTimeout(timeoutId);

if (!r.ok) throw new Error("Network response was not OK");

const response = await r.text();

if (r.headers.get("Content-Type") === "application/json") return JSON.parse(response, reviver);
let response: any = await r.text();

if (r.headers.get("Content-Type")?.startsWith("application/json")) response = JSON.parse(response, reviver);

if (!r.ok) {
throw new Error(response?.error ?? "Something went wrong", {
cause: {
data : response,
status: r.status,
},
});
}

return response;
})
Expand Down
27 changes: 17 additions & 10 deletions src/api/API.node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,21 +63,28 @@ export default abstract class API extends Base {
(res) => {
res.setEncoding("utf8");

// eslint-disable-next-line @typescript-eslint/no-magic-numbers
if (!res.statusCode || res.statusCode < 200 || res.statusCode > 299) {
reject(new Error("Network response was not OK"));

return;
}

let rawData = "";
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let rawData: any = "";

res
.once("error", error => reject(error))
.once("end", () => {
try {
if (res.headers["Content-Type"] === "application/json") resolve(JSON.parse(rawData, reviver));
else resolve(rawData as never);
if (res.headers["content-type"]?.startsWith("application/json")) rawData = JSON.parse(rawData, reviver);

// eslint-disable-next-line @typescript-eslint/no-magic-numbers
if (!res.statusCode || res.statusCode < 200 || res.statusCode > 299) {
reject(new Error(rawData?.error ?? "Something went wrong", {
cause: {
data : rawData,
status: res.statusCode,
},
}));

return;
}

resolve(rawData);
} catch (error) {
reject(error);
}
Expand Down

0 comments on commit 42f6fbe

Please sign in to comment.