diff --git a/index.js b/index.js index e11bfd2..14a5879 100644 --- a/index.js +++ b/index.js @@ -640,4 +640,6 @@ got.UnsupportedProtocolError = class extends StdError { } }; +got.CancelError = PCancelable.CancelError; + module.exports = got; diff --git a/readme.md b/readme.md index 2ac7fc1..16b1c4a 100644 --- a/readme.md +++ b/readme.md @@ -277,6 +277,10 @@ When server redirects you more than 10 times. Includes a `redirectUrls` property When given an unsupported protocol. +#### got.CancelError + +When the request is aborted with `.cancel()`. + ## Aborting the request @@ -296,6 +300,22 @@ request.catch(err => { request.cancel(); ``` +Or + +```js +const request = got(url, options); + +request.catch(err => { + if (err instanceof got.CancelError) { + // Handle cancelation + } + + // Handle other errors +}); + +request.cancel(); +``` + ## Proxies diff --git a/test/cancel.js b/test/cancel.js index 3ed0fdf..caa2d15 100644 --- a/test/cancel.js +++ b/test/cancel.js @@ -85,3 +85,35 @@ test('cancel immediately', async t => { await t.throws(p); await t.notThrows(aborted, 'Request finished instead of aborting.'); }); + +test('recover from cancelation using cancelable promise attribute', async t => { + // Canceled before connection started + const p = got('http://example.com'); + const recover = p.catch(err => { + if (p.canceled) { + return; + } + + throw err; + }); + + p.cancel(); + + await t.notThrows(recover); +}); + +test('recover from cancellation using error instance', async t => { + // Canceled before connection started + const p = got('http://example.com'); + const recover = p.catch(err => { + if (err instanceof got.CancelError) { + return; + } + + throw err; + }); + + p.cancel(); + + await t.notThrows(recover); +});