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", () => {