Skip to content

Commit

Permalink
Simplify the codes
Browse files Browse the repository at this point in the history
  • Loading branch information
jopemachine committed May 13, 2022
1 parent 63f7b08 commit b18f1fe
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
6 changes: 6 additions & 0 deletions source/as-promise/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,12 @@ export default function asPromise<T>(firstRequest?: Request): CancelableRequest<
const emitter = new EventEmitter();

const promise = new PCancelable<T>((resolve, reject, onCancel) => {
firstRequest?.on('error', (error: RequestError) => {
if (error.code === 'ERR_GOR_ABORT_ERROR') {
reject(error);
}
});

onCancel(() => {
globalRequest.destroy();
});
Expand Down
13 changes: 13 additions & 0 deletions source/core/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,3 +170,16 @@ export class RetryError extends RequestError {
this.code = 'ERR_RETRYING';
}
}

/**
An error to be thrown when the request is aborted by AbortController.
DOMException is thrown instead of this Error when DOMException is available.
*/
export class AbortError extends RequestError {
constructor(request: Request, message: string) {
super(message, {}, request);
this.name = 'AbortError';
this.code = 'ERR_GOR_ABORT_ERROR';
this.message = message;
}
}
3 changes: 2 additions & 1 deletion source/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
TimeoutError,
UploadError,
CacheError,
AbortError,
} from './errors.js';
import type {PlainResponse} from './response.js';
import type {PromiseCookieJar, NativeRequestOptions, RetryOptions} from './options.js';
Expand Down Expand Up @@ -236,7 +237,7 @@ export default class Request extends Duplex implements RequestEvents<Request> {
}

this.options.signal?.addEventListener('abort', () => {
this.destroy(new Error('This operation was aborted.'));
this.destroy(new AbortError(this, 'This operation was aborted.'));
});

// Important! If you replace `body` in a handler with another stream, make sure it's readable first.
Expand Down

0 comments on commit b18f1fe

Please sign in to comment.