fastify / under-pressure

Measure process load with automatic handling of "Service Unavailable" plugin for Fastify.
MIT License
341 stars 35 forks source link

bug when setting custom error handler #206

Open Uzlopak opened 1 year ago

Uzlopak commented 1 year ago
          I had a second look at it seems we have bugs in that part, before you even touched it.

https://github.com/fastify/under-pressure/blob/26677abff7385d274eb8836632d253e8fcc76abd/index.js#L107

When opts.exposeStatusRoute.routeSchemaOpts is in Object.assign before our changes, than it means we can not overwrite the error statuscodes.

The same here: https://github.com/fastify/under-pressure/blob/26677abff7385d274eb8836632d253e8fcc76abd/index.js#L113

We could set a custom error handler like this:

    fastify.setErrorHandler((err, request, reply, done) => {
      reply.status(err.statusCode)
        .send({
          code: err.code,
          message: err.message
        })
      done()
    })

a potential unit test would be:

test('check error handler', async t => {
  t.plan(1)
  const fastify = Fastify({ exposeStatusRoute: true })

  fastify.register(underPressure, {
    healthCheck: () => {
      throw new Error('Arbitrary Error')
    },    
    exposeStatusRoute: {
      routeOpts: {
        logLevel: 'silent'
      }
    }
  })

  t.equal((await fastify.inject().get('/').end()).body, '{"code":"FST_UNDER_PRESSURE","message":"Service Unavailable"}')
})

Originally posted by @Uzlopak in https://github.com/fastify/under-pressure/issues/198#issuecomment-1632101053