Skip to content

Commit

Permalink
Add Request to TimeoutError (#267)
Browse files Browse the repository at this point in the history
  • Loading branch information
ByScripts committed Jul 12, 2020
1 parent 2c5d6dd commit b9dbd19
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 7 deletions.
2 changes: 1 addition & 1 deletion index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -375,7 +375,7 @@ declare class HTTPError extends Error {
The error thrown when the request times out.
*/
declare class TimeoutError extends Error {
constructor();
constructor(request: Request);
}

declare const ky: {
Expand Down
11 changes: 6 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -156,27 +156,28 @@ class HTTPError extends Error {
}

class TimeoutError extends Error {
constructor() {
constructor(request) {
super('Request timed out');
this.name = 'TimeoutError';
this.request = request;
}
}

const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

// `Promise.race()` workaround (#91)
const timeout = (promise, ms, abortController) =>
const timeout = (request, ms, abortController) =>
new Promise((resolve, reject) => {
const timeoutID = setTimeout(() => {
if (abortController) {
abortController.abort();
}

reject(new TimeoutError());
reject(new TimeoutError(request));
}, ms);

/* eslint-disable promise/prefer-await-to-then */
promise
globals.fetch(request)
.then(resolve)
.catch(reject)
.then(() => {
Expand Down Expand Up @@ -433,7 +434,7 @@ class Ky {
return globals.fetch(this.request.clone());
}

return timeout(globals.fetch(this.request.clone()), this._options.timeout, this.abortController);
return timeout(this.request.clone(), this._options.timeout, this.abortController);
}

/* istanbul ignore next */
Expand Down
2 changes: 1 addition & 1 deletion index.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ for (const method of requestMethods) {
expectType<typeof ky>(ky.create({}));
expectType<typeof ky>(ky.extend({}));
expectType<InstanceType<typeof ky.HTTPError>>(new ky.HTTPError(new Response()));
expectType<InstanceType<typeof ky.TimeoutError>>(new ky.TimeoutError());
expectType<InstanceType<typeof ky.TimeoutError>>(new ky.TimeoutError(new Request('Test')));

ky(url, {
hooks: {
Expand Down

0 comments on commit b9dbd19

Please sign in to comment.