Skip to content

Commit 7c9abfb

Browse files
fix: surface 'cause' for undici network errors (#642)
1 parent 1e7ea00 commit 7c9abfb

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

src/fetch-wrapper.ts

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,20 @@ export default function fetchWrapper(
131131
if (error instanceof RequestError) throw error;
132132
else if (error.name === "AbortError") throw error;
133133

134-
throw new RequestError(error.message, 500, {
134+
let message = error.message;
135+
136+
// undici throws a TypeError for network errors
137+
// and puts the error message in `error.cause`
138+
// 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;
145+
}
146+
147+
throw new RequestError(message, 500, {
135148
request: requestOptions,
136149
});
137150
});

test/request.test.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -439,6 +439,26 @@ x//0u+zd/R/QRUzLOw4N72/Hu+UG6MNt5iDZFCtapRaKt6OvSBwy8w==
439439
});
440440
});
441441

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

0 commit comments

Comments
 (0)