Skip to content

Commit

Permalink
Fix unhandled exception when lookup returns invalid IP early
Browse files Browse the repository at this point in the history
Fixes #1737
  • Loading branch information
szmarczak committed Jul 31, 2021
1 parent 846e298 commit 2453e5e
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
14 changes: 12 additions & 2 deletions source/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1101,11 +1101,21 @@ export default class Request extends Duplex implements RequestEvents<Request> {
const fn = options.cache ? this._createCacheableRequest : request;

try {
let requestOrResponse = await fn(url, this._requestOptions);
// We can't do `await fn(...)`,
// because stream `error` event can be emitted before `Promise.resolve()`.
let requestOrResponse = fn(url, this._requestOptions);

if (is.promise(requestOrResponse)) {
requestOrResponse = await requestOrResponse;
}

// Fallback
if (is.undefined(requestOrResponse)) {
requestOrResponse = await options.getFallbackRequestFunction()(url, this._requestOptions);
requestOrResponse = options.getFallbackRequestFunction()(url, this._requestOptions);

if (is.promise(requestOrResponse)) {
requestOrResponse = await requestOrResponse;
}
}

if (isClientRequest(requestOrResponse!)) {
Expand Down
12 changes: 12 additions & 0 deletions test/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -357,3 +357,15 @@ test('JSON request custom stringifier', withServer, async (t, server, got) => {
json: payload,
})).body, customStringify(payload));
});

test('ClientRequest can throw before promise resolves', async t => {
await t.throwsAsync(got('http://example.com', {
dnsLookup: ((_hostname: string, _options: unknown, callback: Function) => {
queueMicrotask(() => {
callback(null, 'fe80::0000:0000:0000:0000', 6);
});
}) as any
}), {
code: 'EINVAL'
});
});

0 comments on commit 2453e5e

Please sign in to comment.