From 24b54eace249099e9e945b54766b8498da0cc76f Mon Sep 17 00:00:00 2001 From: uzlopak Date: Mon, 8 Jul 2024 12:47:18 +0200 Subject: [PATCH 1/2] fix: ensure statusCode is always an integer --- src/index.ts | 10 +++++++++- test/request-error.test.ts | 7 +++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/index.ts b/src/index.ts index 0fb3ae8..97a82ba 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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 (this.status !== this.status) { + this.status = 0; + } if ("response" in options) { this.response = options.response; diff --git a/test/request-error.test.ts b/test/request-error.test.ts index fef4b2c..4ab09ca 100644 --- a/test/request-error.test.ts +++ b/test/request-error.test.ts @@ -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", () => { From 1db0a7795f73e2a18c67b3952d64ee865565a4ab Mon Sep 17 00:00:00 2001 From: Aras Abbasi Date: Wed, 10 Jul 2024 22:43:52 +0200 Subject: [PATCH 2/2] Update src/index.ts --- src/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/index.ts b/src/index.ts index 97a82ba..ffda6b2 100644 --- a/src/index.ts +++ b/src/index.ts @@ -42,7 +42,7 @@ export class RequestError extends Error { // If status is not equal to itself, then it is NaN // we set then the status to 0 - if (this.status !== this.status) { + if (Number.isNaN(this.status)) { this.status = 0; }