diff --git a/lib/fetch/index.js b/lib/fetch/index.js index 7388da51ffc..8474936b28d 100644 --- a/lib/fetch/index.js +++ b/lib/fetch/index.js @@ -1760,7 +1760,7 @@ async function httpNetworkFetch ( fetchParams.controller.connection.destroy() // 2. Return the appropriate network error for fetchParams. - return makeAppropriateNetworkError(fetchParams) + return makeAppropriateNetworkError(fetchParams, err) } return makeNetworkError(err) diff --git a/lib/fetch/response.js b/lib/fetch/response.js index 1029dbef533..66c0e50e32b 100644 --- a/lib/fetch/response.js +++ b/lib/fetch/response.js @@ -426,15 +426,15 @@ function filterResponse (response, type) { } // https://fetch.spec.whatwg.org/#appropriate-network-error -function makeAppropriateNetworkError (fetchParams) { +function makeAppropriateNetworkError (fetchParams, err = null) { // 1. Assert: fetchParams is canceled. assert(isCancelled(fetchParams)) // 2. Return an aborted network error if fetchParams is aborted; // otherwise return a network error. return isAborted(fetchParams) - ? makeNetworkError(new DOMException('The operation was aborted.', 'AbortError')) - : makeNetworkError('Request was cancelled.') + ? makeNetworkError(Object.assign(new DOMException('The operation was aborted.', 'AbortError'), { cause: err })) + : makeNetworkError(Object.assign(new DOMException('Request was cancelled.'), { cause: err })) } // https://whatpr.org/fetch/1392.html#initialize-a-response diff --git a/test/proxy-agent.js b/test/proxy-agent.js index a35101234c6..6764cb106e7 100644 --- a/test/proxy-agent.js +++ b/test/proxy-agent.js @@ -443,6 +443,30 @@ test('should throw when proxy does not return 200', async (t) => { t.end() }) +test('pass ProxyAgent proxy status code error when using fetch - #2161', async (t) => { + const server = await buildServer() + const proxy = await buildProxy() + + const serverUrl = `http://localhost:${server.address().port}` + const proxyUrl = `http://localhost:${proxy.address().port}` + + proxy.authenticate = function (req, fn) { + fn(null, false) + } + + const proxyAgent = new ProxyAgent(proxyUrl) + try { + await fetch(serverUrl, { dispatcher: proxyAgent }) + } catch (e) { + t.hasProp(e, 'cause') + } + + server.close() + proxy.close() + proxyAgent.close() + t.end() +}) + test('Proxy via HTTP to HTTPS endpoint', async (t) => { t.plan(4)