Skip to content

Commit

Permalink
fix echoing header in Hapi plugin for error responses (#45)
Browse files Browse the repository at this point in the history
  • Loading branch information
crccheck authored Nov 17, 2020
1 parent 7bbd385 commit 019b926
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/rtracer.js
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,11 @@ const hapiPlugin = ({

if (echoHeader) {
server.ext('onPreResponse', async (request, h) => {
request.response.header(headerName, id())
if (request.response.output) { // Response is a Boom error
request.response.output.headers[headerName] = id()
} else {
request.response.header(headerName, id())
}
return h.continue
})
}
Expand Down
22 changes: 22 additions & 0 deletions tests/hapi.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -349,4 +349,26 @@ describe('cls-rtracer for Hapi', () => {
expect(res.statusCode).toBe(200)
expect(res.headers['x-another-req-id']).toEqual(id)
})

test('echoes the header when the option is set and an error is thrown', async () => {
let id

server = await setupServer({
options: {
echoHeader: true
},
handler: () => {
id = rTracer.id()
throw new Error(id)
}
})

const res = await server.inject({
method: 'get',
url: '/'
})

expect(res.statusCode).toBe(500)
expect(res.headers['x-request-id']).toEqual(id)
})
})

0 comments on commit 019b926

Please sign in to comment.