diff --git a/lib/handlers.js b/lib/handlers.js index 8fdd9584..b1e59015 100644 --- a/lib/handlers.js +++ b/lib/handlers.js @@ -48,9 +48,21 @@ function getProxyEventHandlers(opts) { function defaultErrorHandler(err, req, res) { var host = (req.headers && req.headers.host); + var code = err.code; if (res.writeHead && !res.headersSent) { - res.writeHead(500); + if (/HPE_INVALID/.test(code)) { + res.writeHead(502); + } else { + switch(code) { + case 'ECONNRESET': + case 'ENOTFOUND': + case 'ECONNREFUSED': + res.writeHead(504); + break; + default: res.writeHead(500); + } + } } res.end('Error occured while trying to proxy to: ' + host + req.url); diff --git a/test/e2e/http-proxy-middleware.spec.js b/test/e2e/http-proxy-middleware.spec.js index 6031bd07..c00f29aa 100644 --- a/test/e2e/http-proxy-middleware.spec.js +++ b/test/e2e/http-proxy-middleware.spec.js @@ -395,7 +395,7 @@ describe('E2E http-proxy-middleware', function() { }); it('should handle errors when host is not reachable', function() { - expect(response.statusCode).to.equal(500); + expect(response.statusCode).to.equal(504); }); }); diff --git a/test/unit/handlers.spec.js b/test/unit/handlers.spec.js index fcfdb04c..04db566f 100644 --- a/test/unit/handlers.spec.js +++ b/test/unit/handlers.spec.js @@ -101,9 +101,21 @@ describe('default proxy error handler', function() { errorMessage = undefined; }); - it('should set the http status code to: 500', function() { - proxyError(mockError, mockReq, mockRes, proxyOptions); - expect(httpErrorCode).to.equal(500); + var codes = [ + ['HPE_INVALID_FOO', 502], + ['HPE_INVALID_BAR', 502], + ['ECONNREFUSED', 504], + ['ENOTFOUND', 504], + ['ECONNREFUSED', 504], + ['any', 500], + ]; + codes.forEach(function(item) { + var msg = item[0]; + var code = item[1]; + it('should set the http status code for ' + msg + ' to: ' + code, function() { + proxyError({ code: msg }, mockReq, mockRes, proxyOptions); + expect(httpErrorCode).to.equal(code); + }); }); it('should end the response and return error message', function() {