Skip to content

Commit

Permalink
throw proper error instead of json parse error (#441)
Browse files Browse the repository at this point in the history
* 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>
  • Loading branch information
ihlokalise and Irfan Hodzic authored Mar 13, 2024
1 parent 7f45cee commit 5dca3c1
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
16 changes: 12 additions & 4 deletions src/http_client/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,18 @@ export class ApiRequest {
try {
const response = await fetch(target, options);
let responseJSON;
if (response.status === 204) {
responseJSON = null;
} else {
responseJSON = await response.json();

try {
if (response.status === 204) {
responseJSON = null;
} else {
responseJSON = await response.json();
}
} catch (error) {
return Promise.reject({
message: response.statusText,
code: response.status,
});
}

if (response.ok) {
Expand Down
22 changes: 22 additions & 0 deletions test/lokalise/lokalise_api.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { LokaliseApi, expect, it, describe, Stub } from "../setup.js";
import { MockAgent, setGlobalDispatcher } from "undici";

const project_id = "803826145ba90b42d5d860.46800099";

Expand All @@ -16,6 +17,27 @@ describe("LokaliseApi", function () {
expect(client.clientData.enableCompression).to.be.false;
expect(client.clientData.version).to.eq("api2");
});

it("is expected to reject with proper http message and status code if json is not parsable", async function () {
const mockAgent = new MockAgent();
setGlobalDispatcher(mockAgent);
const mockPool = mockAgent.get("https://api.lokalise.com");

mockPool
.intercept({
path: "/api2/projects/" + project_id,
method: "GET",
})
.reply(429, <string>"Too many requests");

const client = new LokaliseApi({ apiKey: process.env.API_KEY });

try {
expect(await client.projects().get(project_id)).to.throw();
} catch (error) {
expect(error).to.deep.equal({ message: "Too Many Requests", code: 429 });
}
});
});

describe("LokaliseApi host", function () {
Expand Down

0 comments on commit 5dca3c1

Please sign in to comment.