diff --git a/src/fetch-wrapper.ts b/src/fetch-wrapper.ts index d3cb99737..028d2d57f 100644 --- a/src/fetch-wrapper.ts +++ b/src/fetch-wrapper.ts @@ -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, { diff --git a/test/request.test.ts b/test/request.test.ts index b1f957d4f..b8a9ddd2f 100644 --- a/test/request.test.ts +++ b/test/request.test.ts @@ -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" }), });