Skip to content

Commit

Permalink
feat: add better message and code for timeout error (#351)
Browse files Browse the repository at this point in the history
Co-authored-by: Pooya Parsa <[email protected]>
  • Loading branch information
webfansplz and pi0 authored May 16, 2024
1 parent 4faac04 commit f7f9463
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
12 changes: 8 additions & 4 deletions src/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,10 +156,14 @@ export function createFetch(globalOptions: CreateFetchOptions = {}): $Fetch {
// TODO: Can we merge signals?
if (!context.options.signal && context.options.timeout) {
const controller = new AbortController();
abortTimeout = setTimeout(
() => controller.abort(),
context.options.timeout
);
abortTimeout = setTimeout(() => {
const error = new Error(
"[TimeoutError]: The operation was aborted due to timeout"
);
error.name = "TimeoutError";
(error as any).code = 23; // DOMException.TIMEOUT_ERR
controller.abort(error);
}, context.options.timeout);
context.options.signal = controller.signal;
}

Expand Down
13 changes: 13 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,19 @@ describe("ofetch", () => {
expect(race).to.equal("timeout");
});

it("aborting on timeout reason", async () => {
await $fetch(getURL("timeout"), {
timeout: 100,
retry: 0,
}).catch((error) => {
expect(error.cause.message).to.include(
"The operation was aborted due to timeout"
);
expect(error.cause.name).to.equal("TimeoutError");
expect(error.cause.code).to.equal(DOMException.TIMEOUT_ERR);
});
});

it("deep merges defaultOptions", async () => {
const _customFetch = $fetch.create({
query: {
Expand Down

0 comments on commit f7f9463

Please sign in to comment.