Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: error.cause from undici may be instance of Error #643

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions src/fetch-wrapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,12 +136,12 @@ export default function fetchWrapper(
// undici throws a TypeError for network errors
// and puts the error message in `error.cause`
// https://github.com/nodejs/undici/blob/e5c9d703e63cd5ad691b8ce26e3f9a81c598f2e3/lib/fetch/index.js#L227
if (
error instanceof TypeError &&
"cause" in error &&
typeof error.cause === "string"
) {
message = error.cause;
if (error.name === "TypeError" && "cause" in error) {
if (error.cause instanceof Error) {
message = error.cause.message;
} else if (typeof error.cause === "string") {
message = error.cause;
}
}

throw new RequestError(message, 500, {
Expand Down
24 changes: 23 additions & 1 deletion test/request.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -439,7 +439,29 @@ x//0u+zd/R/QRUzLOw4N72/Hu+UG6MNt5iDZFCtapRaKt6OvSBwy8w==
});
});

it("Request TypeError error", () => {
it("Request TypeError error with an Error cause", () => {
const mock = fetchMock.sandbox().get("https://127.0.0.1:8/", {
throws: Object.assign(new TypeError("fetch failed"), {
cause: new Error("bad"),
}),
});

// port: 8 // officially unassigned port. See https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers
return request("GET https://127.0.0.1:8/", {
request: {
fetch: mock,
},
})
.then(() => {
throw new Error("should not resolve");
})
.catch((error) => {
expect(error.status).toEqual(500);
expect(error.message).toEqual("bad");
});
});

it("Request TypeError error with a string cause", () => {
const mock = fetchMock.sandbox().get("https://127.0.0.1:8/", {
throws: Object.assign(new TypeError("fetch failed"), { cause: "bad" }),
});
Expand Down