-
-
Notifications
You must be signed in to change notification settings - Fork 916
/
error.ts
409 lines (336 loc) 路 10.1 KB
/
error.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
import {Buffer} from 'buffer';
import {URL} from 'url';
import {promisify} from 'util';
import net from 'net';
import http from 'http';
import stream from 'stream';
import test from 'ava';
import getStream from 'get-stream';
import is from '@sindresorhus/is';
import got, {RequestError, HTTPError, TimeoutError} from '../source/index.js';
import type Request from '../source/core/index.js';
import withServer from './helpers/with-server.js';
import invalidUrl from './helpers/invalid-url.js';
const pStreamPipeline = promisify(stream.pipeline);
test('properties', withServer, async (t, server, got) => {
server.get('/', (_request, response) => {
response.statusCode = 404;
response.end('not');
});
const url = new URL(server.url);
const error = (await t.throwsAsync<HTTPError>(got('')))!;
t.truthy(error);
t.truthy(error.response);
t.truthy(error.options);
t.true(Object.prototype.propertyIsEnumerable.call(error, 'options'));
t.false(Object.prototype.propertyIsEnumerable.call(error, 'response'));
t.is(error.code, 'ERR_NON_2XX_3XX_RESPONSE');
t.is(error.message, 'Response code 404 (Not Found)');
t.deepEqual(error.options.url, url);
t.is(error.response.headers.connection, 'close');
t.is(error.response.body, 'not');
});
test('catches dns errors', async t => {
const error = (await t.throwsAsync<RequestError>(got('http://doesntexist', {retry: {limit: 0}})))!;
t.truthy(error);
t.regex(error.message, /ENOTFOUND|EAI_AGAIN/);
t.is((error.options.url as URL).host, 'doesntexist');
t.is(error.options.method, 'GET');
t.true(['ENOTFOUND', 'EAI_AGAIN'].includes(error.code));
});
test('`options.body` form error message', async t => {
// @ts-expect-error Error tests
await t.throwsAsync(got.post('https://example.com', {body: Buffer.from('test'), form: ''}),
{
instanceOf: RequestError,
message: 'Expected value which is `predicate returns truthy for any value`, received values of types `string`.',
},
// {message: 'The `body`, `json` and `form` options are mutually exclusive'}
);
});
test('no plain object restriction on json body', withServer, async (t, server, got) => {
server.post('/body', async (request, response) => {
await pStreamPipeline(request, response);
});
class CustomObject {
a = 123;
}
const body = await got.post('body', {json: new CustomObject()}).json();
t.deepEqual(body, {a: 123});
});
test('default status message', withServer, async (t, server, got) => {
server.get('/', (_request, response) => {
response.statusCode = 400;
response.end('body');
});
const error = await t.throwsAsync<HTTPError>(got(''),
{
instanceOf: HTTPError,
message: 'Response code 400 (Bad Request)',
});
t.is(error?.response.statusCode, 400);
t.is(error?.response.statusMessage, 'Bad Request');
});
test('custom status message', withServer, async (t, server, got) => {
server.get('/', (_request, response) => {
response.statusCode = 400;
response.statusMessage = 'Something Exploded';
response.end('body');
});
const error = await t.throwsAsync<HTTPError>(got(''),
{
instanceOf: HTTPError,
message: 'Response code 400 (Something Exploded)',
});
t.is(error?.response.statusCode, 400);
t.is(error?.response.statusMessage, 'Something Exploded');
});
test('custom body', withServer, async (t, server, got) => {
server.get('/', (_request, response) => {
response.statusCode = 404;
response.end('not');
});
const error = await t.throwsAsync<HTTPError>(got(''),
{
instanceOf: HTTPError,
message: 'Response code 404 (Not Found)',
});
t.is(error?.response.statusCode, 404);
t.is(error?.response.body, 'not');
});
test('contains Got options', withServer, async (t, server, got) => {
server.get('/', (_request, response) => {
response.statusCode = 404;
response.end();
});
const options = {
context: {
foo: 'bar',
},
} as const;
const error = await t.throwsAsync<HTTPError>(got(options),
{
instanceOf: HTTPError,
message: 'Response code 404 (Not Found)',
});
t.is(error?.response.statusCode, 404);
t.is(error?.options.context.foo, options.context.foo);
});
test.failing('empty status message is overriden by the default one', withServer, async (t, server, got) => {
server.get('/', (_request, response) => {
response.writeHead(400, '');
response.end('body');
});
const error = await t.throwsAsync<HTTPError>(got(''),
{
instanceOf: HTTPError,
message: 'Response code 400 (Bad Request)',
});
t.is(error?.response.statusCode, 400);
t.is(error?.response.statusMessage, http.STATUS_CODES[400]);
});
test('`http.request` error', async t => {
await t.throwsAsync(got('https://example.com', {
request() {
throw new TypeError('The header content contains invalid characters');
},
}), {
instanceOf: RequestError,
message: 'The header content contains invalid characters',
code: 'ERR_GOT_REQUEST_ERROR',
});
});
test('`http.request` pipe error', async t => {
const message = 'snap!';
await t.throwsAsync(got('https://example.com', {
// @ts-expect-error Error tests
request() {
const proxy = new stream.PassThrough();
const anyProxy = proxy as any;
anyProxy.socket = {
remoteAddress: '',
prependOnceListener() {},
};
anyProxy.headers = {};
anyProxy.abort = () => {};
proxy.resume();
proxy.read = () => {
proxy.destroy(new Error(message));
return null;
};
return proxy;
},
throwHttpErrors: false,
}), {
instanceOf: RequestError,
message,
});
});
test('`http.request` error through CacheableRequest', async t => {
await t.throwsAsync(got('https://example.com', {
request() {
throw new TypeError('The header content contains invalid characters');
},
cache: new Map(),
}), {
instanceOf: RequestError,
message: 'The header content contains invalid characters',
});
});
test('returns a stream even if normalization fails', async t => {
const stream = got('https://example.com', {
isStream: true,
// @ts-expect-error Testing purposes
hooks: false,
}) as unknown as Request;
await t.throwsAsync(getStream(stream), {
instanceOf: RequestError,
message: 'Expected value which is `Object`, received value of type `boolean`.',
});
});
test('normalization errors using convenience methods', async t => {
const url = 'undefined/https://example.com';
{
const error = await t.throwsAsync(got(url).json());
invalidUrl(t, error!, url);
}
{
const error = await t.throwsAsync(got(url).text());
invalidUrl(t, error!, url);
}
{
const error = await t.throwsAsync(got(url).buffer());
invalidUrl(t, error!, url);
}
});
test('errors can have request property', withServer, async (t, server, got) => {
server.get('/', (_request, response) => {
response.statusCode = 404;
response.end();
});
const error = await t.throwsAsync<HTTPError>(got(''));
t.truthy(error?.response);
t.truthy(error?.request.downloadProgress);
});
test('promise does not hang on timeout on HTTP error', withServer, async (t, server, got) => {
server.get('/', (_request, response) => {
response.statusCode = 404;
response.write('asdf');
});
await t.throwsAsync(got({
timeout: {
request: 100,
},
}), {
instanceOf: TimeoutError,
code: 'ETIMEDOUT',
});
});
test('no uncaught parse errors', async t => {
const server = net.createServer();
const listen = promisify(server.listen.bind(server));
const close = promisify(server.close.bind(server));
await listen();
server.on('connection', socket => {
socket.resume();
socket.end([
'HTTP/1.1 404 Not Found',
'transfer-encoding: chunked',
'',
'0',
'',
'',
].join('\r\n'));
});
await t.throwsAsync(got.head(`http://localhost:${(server.address() as net.AddressInfo).port}`), {
instanceOf: RequestError,
message: /^Parse Error/,
});
await close();
});
test('no uncaught parse errors #2', async t => {
const server = net.createServer();
const listen = promisify(server.listen.bind(server));
const close = promisify(server.close.bind(server));
await listen();
server.on('connection', socket => {
socket.resume();
socket.write([
'HTTP/1.1 200 OK',
'content-length: 1',
'',
'0a',
].join('\r\n'));
});
await t.throwsAsync(got(`http://localhost:${(server.address() as net.AddressInfo).port}`), {
instanceOf: RequestError,
message: /^Parse Error/,
});
await close();
});
// Fails randomly on Node 10:
// Blocked by https://github.com/istanbuljs/nyc/issues/619
// eslint-disable-next-line ava/no-skip-test
test.skip('the old stacktrace is recovered', async t => {
const error = await t.throwsAsync(got('https://example.com', {
request() {
throw new Error('foobar');
},
}));
t.true(error?.stack!.includes('at Object.request'));
// The first `at get` points to where the error was wrapped,
// the second `at get` points to the real cause.
t.not(error?.stack!.indexOf('at get'), error?.stack!.lastIndexOf('at get'));
});
test.serial('custom stack trace', withServer, async (t, _server, got) => {
// eslint-disable-next-line @typescript-eslint/naming-convention
const ErrorCaptureStackTrace = Error.captureStackTrace;
const enable = () => {
Error.captureStackTrace = (target: {stack: any}) => {
target.stack = [
'line 1',
'line 2',
];
};
};
const disable = () => {
Error.captureStackTrace = ErrorCaptureStackTrace;
};
// Node.js default behavior
{
const stream = got.stream('');
stream.destroy(new Error('oh no'));
const caught = await t.throwsAsync(getStream(stream));
t.is(is(caught?.stack), 'string');
}
// Passing a custom error
{
enable();
const error = new Error('oh no');
disable();
const stream = got.stream('');
stream.destroy(error);
const caught = await t.throwsAsync(getStream(stream));
t.is(is(caught?.stack), 'string');
}
// Custom global behavior
{
enable();
const error = new Error('oh no');
const stream = got.stream('');
stream.destroy(error);
const caught = await t.throwsAsync(getStream(stream));
t.is(is(caught?.stack), 'Array');
disable();
}
// Passing a default error that needs some processing
{
const error = new Error('oh no');
enable();
const stream = got.stream('');
stream.destroy(error);
const caught = await t.throwsAsync(getStream(stream));
t.is(is(caught?.stack), 'Array');
disable();
}
});