Skip to content

Commit

Permalink
feat: call events.error handler from error callback (#70)
Browse files Browse the repository at this point in the history
Fixes #69
  • Loading branch information
whenlit authored Dec 5, 2022
1 parent 0d9619b commit b14e202
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
8 changes: 7 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,13 @@ module.exports = (path, options) => {
resolve()
})

proxy.web(ctx.req, ctx.res, httpProxyOpts, e => {
proxy.web(ctx.req, ctx.res, httpProxyOpts, (e, ...args) => {
const errorHandler = proxyEventHandlers.error && proxyEventHandlers.error.get(ctx.req[REQUEST_IDENTIFIER])

if (typeof errorHandler === 'function') {
errorHandler(e, ...args) // If this error handler sends the headers, the ctx.status setter below is ignored
}

const status = {
ECONNREFUSED: 503,
ETIMEOUT: 504
Expand Down
40 changes: 40 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ describe('tests for koa proxies', () => {
case '/500':
ctx.status = 500
break
case '/error':
ctx.req.destroy()
break
default:
return next()
}
Expand Down Expand Up @@ -271,6 +274,43 @@ describe('tests for koa proxies', () => {
sinon.assert.notCalled(proxyInvalidEventSpy)
})

describe('when an error handler is specified', () => {
let options

beforeEach(() => {
options = {
target: 'http://127.0.0.1:12306',
changeOrigin: true,
events: {}
}

const proxyMiddleware = proxy('/error', options)

server = startServer(3000, proxyMiddleware)
})

it('does not set the status in the default error handler when events.error is specified and ends the response', async () => {
options.events.error = sinon.stub().callsFake((e, req, res) => {
res.writeHead(505, 'Something went wrong. And we are reporting a custom error message.').end()
})

const ret = await chai.request(server).get('/error')
expect(ret).to.have.status(505)
expect(ret.res.statusMessage).to.eql('Something went wrong. And we are reporting a custom error message.')

sinon.assert.calledOnce(options.events.error)
})

it('does set the status in the default error handler when events.error is specified but does not end the response', async () => {
options.events.error = sinon.spy()

const ret = await chai.request(server).get('/error')
expect(ret).to.have.status(500)

sinon.assert.calledOnce(options.events.error)
})
})

it('log', async () => {
// spies
const logSpy = sinon.spy(console, 'log')
Expand Down

0 comments on commit b14e202

Please sign in to comment.