Skip to content

Commit 734f5e0

Browse files
committed
fixed: Handle proxy errors
1 parent 537aed2 commit 734f5e0

File tree

4 files changed

+57
-3
lines changed

4 files changed

+57
-3
lines changed

index.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,16 @@ var httpProxyMiddleware = function (context, opts) {
66
var proxyOptions = opts || {};
77
var proxy = httpProxy.createProxyServer(proxyOptions);
88

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

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

15+
proxy.on('error', function (err, req, res) {
16+
utils.proxyError(err, req, res, proxyOptions);
17+
});
18+
1519
return fnProxyMiddleWare;
1620

1721
function fnProxyMiddleWare (req, res, next) {

lib/utils.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
module.exports = {
2-
hasContext: require('./utils/has-context'),
3-
proxyReqHost: require('./utils/proxy-req-host')
2+
hasContext : require('./utils/has-context'),
3+
proxyReqHost : require('./utils/proxy-req-host'),
4+
proxyError : require('./utils/proxy-error')
45
}

lib/utils/proxy-error.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
module.exports = function(err, req, res, proxyOptions) {
2+
var targetUri = proxyOptions.target.host + req.url;
3+
console.log('[HPM] Proxy error:', err.code, targetUri);
4+
5+
res.writeHead(500);
6+
res.end('Error occured while trying to proxy to: '+ proxyOptions.target.host + req.url);
7+
};

test/utils-proxy-error.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
var expect = require('chai').expect;
2+
var proxyError = require('../lib/utils/proxy-error');
3+
4+
var mockError = {
5+
code : 'ECONNREFUSED'
6+
};
7+
8+
9+
var mockReq = {
10+
url : '/api'
11+
};
12+
13+
var proxyOptions = {
14+
target : {
15+
host : 'localhost.dev'
16+
}
17+
};
18+
19+
describe('utils#proxyError(err, req, res, proxyOptions)', function () {
20+
21+
it('should set the header: host to match the target host', function () {
22+
var httpErrorCode;
23+
var errorMessage;
24+
25+
var mockRes = {
26+
writeHead : function (v) {
27+
httpErrorCode = v;
28+
return v;
29+
},
30+
end : function (v) {
31+
errorMessage = v;
32+
return v;
33+
}
34+
};
35+
36+
proxyError(mockError, mockReq, mockRes, proxyOptions);
37+
38+
expect(httpErrorCode).to.equal(500);
39+
expect(errorMessage).to.equal('Error occured while trying to proxy to: localhost.dev/api');
40+
});
41+
42+
});

0 commit comments

Comments
 (0)