From b18f1fe29958c160a06dc3f534d87c0b48ac0e05 Mon Sep 17 00:00:00 2001 From: Gyubong Lee Date: Fri, 13 May 2022 12:00:23 +0900 Subject: [PATCH] Simplify the codes --- source/as-promise/index.ts | 6 ++++++ source/core/errors.ts | 13 +++++++++++++ source/core/index.ts | 3 ++- 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/source/as-promise/index.ts b/source/as-promise/index.ts index 95ce06dd2..769cd16e7 100644 --- a/source/as-promise/index.ts +++ b/source/as-promise/index.ts @@ -29,6 +29,12 @@ export default function asPromise(firstRequest?: Request): CancelableRequest< const emitter = new EventEmitter(); const promise = new PCancelable((resolve, reject, onCancel) => { + firstRequest?.on('error', (error: RequestError) => { + if (error.code === 'ERR_GOR_ABORT_ERROR') { + reject(error); + } + }); + onCancel(() => { globalRequest.destroy(); }); diff --git a/source/core/errors.ts b/source/core/errors.ts index fc48166f2..ff347a1a3 100644 --- a/source/core/errors.ts +++ b/source/core/errors.ts @@ -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; + } +} diff --git a/source/core/index.ts b/source/core/index.ts index 3e1a35114..c011e0d20 100644 --- a/source/core/index.ts +++ b/source/core/index.ts @@ -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'; @@ -236,7 +237,7 @@ export default class Request extends Duplex implements RequestEvents { } 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.