Skip to content

fix: surface 'cause' for undici network errors #642

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

Merged
merged 2 commits into from
Oct 6, 2023
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
15 changes: 14 additions & 1 deletion src/fetch-wrapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,20 @@ export default function fetchWrapper(
if (error instanceof RequestError) throw error;
else if (error.name === "AbortError") throw error;

throw new RequestError(error.message, 500, {
let message = error.message;

// 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;
}

throw new RequestError(message, 500, {
request: requestOptions,
});
});
Expand Down
20 changes: 20 additions & 0 deletions test/request.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -439,6 +439,26 @@ x//0u+zd/R/QRUzLOw4N72/Hu+UG6MNt5iDZFCtapRaKt6OvSBwy8w==
});
});

it("Request TypeError error", () => {
const mock = fetchMock.sandbox().get("https://127.0.0.1:8/", {
throws: Object.assign(new TypeError("fetch failed"), { cause: "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("custom user-agent", () => {
const mock = fetchMock
.sandbox()
Expand Down