Skip to content
This repository was archived by the owner on Feb 2, 2024. It is now read-only.

#92 feat: add custom error handling option #93

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
7 changes: 7 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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) {
Expand Down
17 changes: 17 additions & 0 deletions test/4.opts.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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')({
Expand All @@ -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)
}
})
})
Expand Down Expand Up @@ -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()
Expand Down