From 6eb863401613f29952d36d888159ef0969107a1d Mon Sep 17 00:00:00 2001 From: Aras Abbasi Date: Thu, 11 Jul 2024 00:47:05 +0200 Subject: [PATCH] fix: ensure statusCode is always an integer (#439) * fix: ensure statusCode is always an integer * Update src/index.ts --- 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..ffda6b2 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 (Number.isNaN(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", () => {