diff --git a/README.md b/README.md index a25742a..b84262f 100644 --- a/README.md +++ b/README.md @@ -152,6 +152,9 @@ Called when an http response is received from the source. The default behavior is `pump(stream, res)`, which will be disabled if the option is specified. +##### onError(err, req, res) +Called when an error is thrown from the source. If this option is specified, the default error handling will not be applied. + ##### rewriteRequestHeaders(req, headers) Called to rewrite the headers of the request, before them being sent to the downstream server. It must return the new headers object. diff --git a/index.js b/index.js index ea60c34..d98caad 100644 --- a/index.js +++ b/index.js @@ -38,6 +38,7 @@ function fastProxy (opts = {}) { const onResponse = opts.onResponse const rewriteHeaders = opts.rewriteHeaders || rewriteHeadersNoOp const rewriteRequestHeaders = opts.rewriteRequestHeaders || rewriteRequestHeadersNoOp + const onError = opts.onError const url = getReqUrl(source || req.url, cache, base, opts) const sourceHttp2 = req.httpVersionMajor === 2 @@ -88,6 +89,12 @@ function fastProxy (opts = {}) { } request(reqParams, (err, response) => { if (err) { + // allow for errors to be passed to a custom callback + if (onError) { + onError(err, req, res) + return + } + // check if response has already been sent and all data has been flushed // before configuring error response headers if (res.sent === false || res.writableFinished === false) { diff --git a/test/4.opts.test.js b/test/4.opts.test.js index db67cda..a113d18 100644 --- a/test/4.opts.test.js +++ b/test/4.opts.test.js @@ -17,6 +17,10 @@ nock('http://dev.com') url: 'http://dev.com' }) +nock('http://dev.error') + .get('/service/error') + .replyWithError('Error') + describe('fast-proxy smoke', () => { it('init', async () => { const fastProxy = require('../index')({ @@ -40,6 +44,10 @@ describe('fast-proxy smoke', () => { queryString: { age: 33 }, onResponse (req, res, stream) { pump(stream, res) + }, + onError (err, req, res) { + res.statusCode = 418 + res.send(err.code) } }) }) @@ -99,6 +107,15 @@ describe('fast-proxy smoke', () => { .expect(302) }) + it('should allow for errors to be handled', async () => { + await request(gHttpServer) + .get('/service/error') + .set('base', 'http://dev.com') + .then(response => { + expect(response.statusCode).to.equal(418) + }) + }) + it('close all', async () => { close() await gateway.close()