Skip to content

Commit c67f902

Browse files
author
Nikhil Gupta
authored
fix: error.cause from undici may be instance of Error (#643)
Fix how Undici network errors are surfaced
1 parent 7c9abfb commit c67f902

File tree

2 files changed

+29
-7
lines changed

2 files changed

+29
-7
lines changed

src/fetch-wrapper.ts

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -136,12 +136,12 @@ export default function fetchWrapper(
136136
// undici throws a TypeError for network errors
137137
// and puts the error message in `error.cause`
138138
// https://github.com/nodejs/undici/blob/e5c9d703e63cd5ad691b8ce26e3f9a81c598f2e3/lib/fetch/index.js#L227
139-
if (
140-
error instanceof TypeError &&
141-
"cause" in error &&
142-
typeof error.cause === "string"
143-
) {
144-
message = error.cause;
139+
if (error.name === "TypeError" && "cause" in error) {
140+
if (error.cause instanceof Error) {
141+
message = error.cause.message;
142+
} else if (typeof error.cause === "string") {
143+
message = error.cause;
144+
}
145145
}
146146

147147
throw new RequestError(message, 500, {

test/request.test.ts

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -439,7 +439,29 @@ x//0u+zd/R/QRUzLOw4N72/Hu+UG6MNt5iDZFCtapRaKt6OvSBwy8w==
439439
});
440440
});
441441

442-
it("Request TypeError error", () => {
442+
it("Request TypeError error with an Error cause", () => {
443+
const mock = fetchMock.sandbox().get("https://127.0.0.1:8/", {
444+
throws: Object.assign(new TypeError("fetch failed"), {
445+
cause: new Error("bad"),
446+
}),
447+
});
448+
449+
// port: 8 // officially unassigned port. See https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers
450+
return request("GET https://127.0.0.1:8/", {
451+
request: {
452+
fetch: mock,
453+
},
454+
})
455+
.then(() => {
456+
throw new Error("should not resolve");
457+
})
458+
.catch((error) => {
459+
expect(error.status).toEqual(500);
460+
expect(error.message).toEqual("bad");
461+
});
462+
});
463+
464+
it("Request TypeError error with a string cause", () => {
443465
const mock = fetchMock.sandbox().get("https://127.0.0.1:8/", {
444466
throws: Object.assign(new TypeError("fetch failed"), { cause: "bad" }),
445467
});

0 commit comments

Comments
 (0)