Skip to content

Commit

Permalink
fix: error.cause from undici may be instance of Error (#643)
Browse files Browse the repository at this point in the history
Fix how Undici network errors are surfaced
  • Loading branch information
nikhilgupta345 authored Oct 9, 2023
1 parent 7c9abfb commit c67f902
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 7 deletions.
12 changes: 6 additions & 6 deletions src/fetch-wrapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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, {
Expand Down
24 changes: 23 additions & 1 deletion test/request.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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" }),
});
Expand Down

0 comments on commit c67f902

Please sign in to comment.