Skip to content

Commit

Permalink
fix: surface 'cause' for undici network errors (#642)
Browse files Browse the repository at this point in the history
  • Loading branch information
nikhilgupta345 authored Oct 6, 2023
1 parent 1e7ea00 commit 7c9abfb
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
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

0 comments on commit 7c9abfb

Please sign in to comment.