Skip to content

Commit b55f79e

Browse files
dinoboffsindresorhus
authored andcommitted
Expose CancelError (#378)
1 parent 8ccdeac commit b55f79e

3 files changed

Lines changed: 54 additions & 0 deletions

File tree

index.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -640,4 +640,6 @@ got.UnsupportedProtocolError = class extends StdError {
640640
}
641641
};
642642

643+
got.CancelError = PCancelable.CancelError;
644+
643645
module.exports = got;

readme.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -277,6 +277,10 @@ When server redirects you more than 10 times. Includes a `redirectUrls` property
277277

278278
When given an unsupported protocol.
279279

280+
#### got.CancelError
281+
282+
When the request is aborted with `.cancel()`.
283+
280284

281285
## Aborting the request
282286

@@ -296,6 +300,22 @@ request.catch(err => {
296300
request.cancel();
297301
```
298302

303+
Or
304+
305+
```js
306+
const request = got(url, options);
307+
308+
request.catch(err => {
309+
if (err instanceof got.CancelError) {
310+
// Handle cancelation
311+
}
312+
313+
// Handle other errors
314+
});
315+
316+
request.cancel();
317+
```
318+
299319

300320
## Proxies
301321

test/cancel.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,3 +85,35 @@ test('cancel immediately', async t => {
8585
await t.throws(p);
8686
await t.notThrows(aborted, 'Request finished instead of aborting.');
8787
});
88+
89+
test('recover from cancelation using cancelable promise attribute', async t => {
90+
// Canceled before connection started
91+
const p = got('http://example.com');
92+
const recover = p.catch(err => {
93+
if (p.canceled) {
94+
return;
95+
}
96+
97+
throw err;
98+
});
99+
100+
p.cancel();
101+
102+
await t.notThrows(recover);
103+
});
104+
105+
test('recover from cancellation using error instance', async t => {
106+
// Canceled before connection started
107+
const p = got('http://example.com');
108+
const recover = p.catch(err => {
109+
if (err instanceof got.CancelError) {
110+
return;
111+
}
112+
113+
throw err;
114+
});
115+
116+
p.cancel();
117+
118+
await t.notThrows(recover);
119+
});

0 commit comments

Comments
 (0)