Skip to content

Commit 60594ce

Browse files
szmarczakoctet-stream
authored andcommitted
Fix unhandled exception when lookup returns invalid IP early
Fixes sindresorhus#1737
1 parent 75c0f67 commit 60594ce

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

source/core/index.ts

+12-2
Original file line numberDiff line numberDiff line change
@@ -1113,11 +1113,21 @@ export default class Request extends Duplex implements RequestEvents<Request> {
11131113
const fn = options.cache ? this._createCacheableRequest : request;
11141114

11151115
try {
1116-
let requestOrResponse = await fn(url, this._requestOptions);
1116+
// We can't do `await fn(...)`,
1117+
// because stream `error` event can be emitted before `Promise.resolve()`.
1118+
let requestOrResponse = fn(url, this._requestOptions);
1119+
1120+
if (is.promise(requestOrResponse)) {
1121+
requestOrResponse = await requestOrResponse;
1122+
}
11171123

11181124
// Fallback
11191125
if (is.undefined(requestOrResponse)) {
1120-
requestOrResponse = await options.getFallbackRequestFunction()(url, this._requestOptions);
1126+
requestOrResponse = options.getFallbackRequestFunction()(url, this._requestOptions);
1127+
1128+
if (is.promise(requestOrResponse)) {
1129+
requestOrResponse = await requestOrResponse;
1130+
}
11211131
}
11221132

11231133
if (isClientRequest(requestOrResponse!)) {

test/http.ts

+12
Original file line numberDiff line numberDiff line change
@@ -357,3 +357,15 @@ test('JSON request custom stringifier', withServer, async (t, server, got) => {
357357
json: payload,
358358
})).body, customStringify(payload));
359359
});
360+
361+
test('ClientRequest can throw before promise resolves', async t => {
362+
await t.throwsAsync(got('http://example.com', {
363+
dnsLookup: ((_hostname: string, _options: unknown, callback: Function) => {
364+
queueMicrotask(() => {
365+
callback(null, 'fe80::0000:0000:0000:0000', 6);
366+
});
367+
}) as any
368+
}), {
369+
code: 'EINVAL'
370+
});
371+
});

0 commit comments

Comments
 (0)