Skip to content

Commit

Permalink
fix(adapter-node-http): Fix unhandled rejection if connection fails (#…
Browse files Browse the repository at this point in the history
…160)

An unhandled promise rejection was thrown if a socket could not be opened,
which prevents handling the error gracefully in a consuming app.
  • Loading branch information
dustinsoftware authored and jasonmit committed Jan 16, 2019
1 parent 05b17cb commit 12fcfa7
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -138,17 +138,16 @@ export default class TransportWrapper {
...NodeUrl.parse(pollyRequest.url)
});

request.on('error', error => {
throw error;
const requestPromise = new Promise((resolve, reject) => {
request.once('response', response => resolve(response));
request.once('error', reject);
});

// Write the request body
chunks.forEach(chunk => request.write(chunk));

const response = await new Promise(resolve => {
request.once('response', response => resolve(response));
request.end();
});
request.end();
const response = await requestPromise;

const responseBody = await new Promise((resolve, reject) => {
const chunks = [];
Expand Down Expand Up @@ -270,13 +269,18 @@ export default class TransportWrapper {
parsedUrl.set('hostname', hostname);
parsedUrl.set('port', port !== '80' ? port : '');

adapter.handleRequest({
method,
headers,
url: parsedUrl.href,
body: chunks,
requestArguments: [wrapper, req, args]
});
adapter
.handleRequest({
method,
headers,
url: parsedUrl.href,
body: chunks,
requestArguments: [wrapper, req, args]
})
.catch(e => {
// This allows the consumer to handle the error gracefully
req.emit('error', e);
});
};

return req;
Expand Down
3 changes: 3 additions & 0 deletions packages/@pollyjs/core/src/utils/deferred-promise.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ export default function defer() {
_reject = reject;
});

// Prevent unhandled rejection warnings
promise.catch(() => {});

promise.resolve = _resolve;
promise.reject = _reject;

Expand Down

0 comments on commit 12fcfa7

Please sign in to comment.