Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add better message and code for timeout error #351

Merged
merged 7 commits into from
May 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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