Skip to content

Commit

Permalink
fix: ensure statusCode is always an integer (#439)
Browse files Browse the repository at this point in the history
* fix: ensure statusCode is always an integer

* Update src/index.ts
  • Loading branch information
Uzlopak authored Jul 10, 2024
1 parent bde5ce7 commit 6eb8634
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
10 changes: 9 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,15 @@ export class RequestError extends Error {
}

this.name = "HttpError";
this.status = statusCode;

// Implicit coercion to number if statusCode is a string
this.status = Number.parseInt(statusCode as unknown as string);

// If status is not equal to itself, then it is NaN
// we set then the status to 0
if (Number.isNaN(this.status)) {
this.status = 0;
}

if ("response" in options) {
this.response = options.response;
Expand Down
7 changes: 7 additions & 0 deletions test/request-error.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,13 @@ describe("RequestError", () => {
test("sets .status", () => {
expect(new RequestError("test", 123, mockOptions).status).toEqual(123);
expect(new RequestError("test", 404, mockOptions).status).toEqual(404);
// @ts-expect-error
expect(new RequestError("test", "404", mockOptions).status).toEqual(404);
expect(new RequestError("test", NaN, mockOptions).status).toEqual(0);
// @ts-expect-error
expect(new RequestError("test", [], mockOptions).status).toEqual(0);
// @ts-expect-error
expect(new RequestError("test", new Date(), mockOptions).status).toEqual(0);
});

test("sets .request", () => {
Expand Down

0 comments on commit 6eb8634

Please sign in to comment.