diff --git a/src/rtracer.js b/src/rtracer.js index f419c0a..cf54be1 100644 --- a/src/rtracer.js +++ b/src/rtracer.js @@ -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 }) } diff --git a/tests/hapi.test.js b/tests/hapi.test.js index 79d417c..1632cec 100644 --- a/tests/hapi.test.js +++ b/tests/hapi.test.js @@ -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) + }) })