Skip to content

Commit 6eb8634

Browse files
authored
fix: ensure statusCode is always an integer (#439)
* fix: ensure statusCode is always an integer * Update src/index.ts
1 parent bde5ce7 commit 6eb8634

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

src/index.ts

+9-1
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,15 @@ export class RequestError extends Error {
3636
}
3737

3838
this.name = "HttpError";
39-
this.status = statusCode;
39+
40+
// Implicit coercion to number if statusCode is a string
41+
this.status = Number.parseInt(statusCode as unknown as string);
42+
43+
// If status is not equal to itself, then it is NaN
44+
// we set then the status to 0
45+
if (Number.isNaN(this.status)) {
46+
this.status = 0;
47+
}
4048

4149
if ("response" in options) {
4250
this.response = options.response;

test/request-error.test.ts

+7
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,13 @@ describe("RequestError", () => {
3434
test("sets .status", () => {
3535
expect(new RequestError("test", 123, mockOptions).status).toEqual(123);
3636
expect(new RequestError("test", 404, mockOptions).status).toEqual(404);
37+
// @ts-expect-error
38+
expect(new RequestError("test", "404", mockOptions).status).toEqual(404);
39+
expect(new RequestError("test", NaN, mockOptions).status).toEqual(0);
40+
// @ts-expect-error
41+
expect(new RequestError("test", [], mockOptions).status).toEqual(0);
42+
// @ts-expect-error
43+
expect(new RequestError("test", new Date(), mockOptions).status).toEqual(0);
3744
});
3845

3946
test("sets .request", () => {

0 commit comments

Comments
 (0)