Skip to content

Commit

Permalink
fixed: Handle proxy errors
Browse files Browse the repository at this point in the history
  • Loading branch information
chimurai committed Mar 31, 2015
1 parent 537aed2 commit 734f5e0
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 3 deletions.
6 changes: 5 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,16 @@ var httpProxyMiddleware = function (context, opts) {
var proxyOptions = opts || {};
var proxy = httpProxy.createProxyServer(proxyOptions);

console.log('[http-proxy-middleware] Proxy created:', context, proxyOptions.target);
console.log('[HPM] Proxy created:', context, proxyOptions.target);

if (proxyOptions.proxyHost) {
proxy.on('proxyReq', utils.proxyReqHost);
}

proxy.on('error', function (err, req, res) {
utils.proxyError(err, req, res, proxyOptions);
});

return fnProxyMiddleWare;

function fnProxyMiddleWare (req, res, next) {
Expand Down
5 changes: 3 additions & 2 deletions lib/utils.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
module.exports = {
hasContext: require('./utils/has-context'),
proxyReqHost: require('./utils/proxy-req-host')
hasContext : require('./utils/has-context'),
proxyReqHost : require('./utils/proxy-req-host'),
proxyError : require('./utils/proxy-error')
}
7 changes: 7 additions & 0 deletions lib/utils/proxy-error.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module.exports = function(err, req, res, proxyOptions) {
var targetUri = proxyOptions.target.host + req.url;
console.log('[HPM] Proxy error:', err.code, targetUri);

res.writeHead(500);
res.end('Error occured while trying to proxy to: '+ proxyOptions.target.host + req.url);
};
42 changes: 42 additions & 0 deletions test/utils-proxy-error.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
var expect = require('chai').expect;
var proxyError = require('../lib/utils/proxy-error');

var mockError = {
code : 'ECONNREFUSED'
};


var mockReq = {
url : '/api'
};

var proxyOptions = {
target : {
host : 'localhost.dev'
}
};

describe('utils#proxyError(err, req, res, proxyOptions)', function () {

it('should set the header: host to match the target host', function () {
var httpErrorCode;
var errorMessage;

var mockRes = {
writeHead : function (v) {
httpErrorCode = v;
return v;
},
end : function (v) {
errorMessage = v;
return v;
}
};

proxyError(mockError, mockReq, mockRes, proxyOptions);

expect(httpErrorCode).to.equal(500);
expect(errorMessage).to.equal('Error occured while trying to proxy to: localhost.dev/api');
});

});

0 comments on commit 734f5e0

Please sign in to comment.