Skip to content

Commit 5dca3c1

Browse files
ihlokaliseIrfan Hodzic
and
Irfan Hodzic
authored
throw proper error instead of json parse error (#441)
* throw propper error instead of json parse error * test for proper promise rejection * remove .only --------- Co-authored-by: Irfan Hodzic <[email protected]@Irfans-MacBook-Pro.local>
1 parent 7f45cee commit 5dca3c1

File tree

2 files changed

+34
-4
lines changed

2 files changed

+34
-4
lines changed

src/http_client/base.ts

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -65,10 +65,18 @@ export class ApiRequest {
6565
try {
6666
const response = await fetch(target, options);
6767
let responseJSON;
68-
if (response.status === 204) {
69-
responseJSON = null;
70-
} else {
71-
responseJSON = await response.json();
68+
69+
try {
70+
if (response.status === 204) {
71+
responseJSON = null;
72+
} else {
73+
responseJSON = await response.json();
74+
}
75+
} catch (error) {
76+
return Promise.reject({
77+
message: response.statusText,
78+
code: response.status,
79+
});
7280
}
7381

7482
if (response.ok) {

test/lokalise/lokalise_api.spec.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { LokaliseApi, expect, it, describe, Stub } from "../setup.js";
2+
import { MockAgent, setGlobalDispatcher } from "undici";
23

34
const project_id = "803826145ba90b42d5d860.46800099";
45

@@ -16,6 +17,27 @@ describe("LokaliseApi", function () {
1617
expect(client.clientData.enableCompression).to.be.false;
1718
expect(client.clientData.version).to.eq("api2");
1819
});
20+
21+
it("is expected to reject with proper http message and status code if json is not parsable", async function () {
22+
const mockAgent = new MockAgent();
23+
setGlobalDispatcher(mockAgent);
24+
const mockPool = mockAgent.get("https://api.lokalise.com");
25+
26+
mockPool
27+
.intercept({
28+
path: "/api2/projects/" + project_id,
29+
method: "GET",
30+
})
31+
.reply(429, <string>"Too many requests");
32+
33+
const client = new LokaliseApi({ apiKey: process.env.API_KEY });
34+
35+
try {
36+
expect(await client.projects().get(project_id)).to.throw();
37+
} catch (error) {
38+
expect(error).to.deep.equal({ message: "Too Many Requests", code: 429 });
39+
}
40+
});
1941
});
2042

2143
describe("LokaliseApi host", function () {

0 commit comments

Comments
 (0)