immobiliare/fastify-sentry

Fastify-Sentry is causing error reply status codes to be 200

Closed this issue · 5 comments

I have a route with a Knex instance throwing SQL errors. I use an error handler in my app.ts file to catch these and set a generic error message.

fastify.setErrorHandler((error, request, reply) => {

    if ((process.env.NODE_ENV || 'development') === 'production') {
      reply.status(500).send({ message: "Internal Server Error"});`

However, these thrown errors are coming back with a 2xx status code and a response body
{"error":500,"message":"Internal Server Error"}

image
fastify.withTypeProvider<ZodTypeProvider>().route({
    method: "DELETE",
    url: "/ingredients/:id",
    onRequest: [fastify.authenticate, fastify.isAdmin],
    schema: {
      params: z.object({
        id: z.string()
      }),
    },
    handler: async (request, reply) => {
      const ingredientId = Number(request.params.id);
      await fastify.knex('ingredient')
        .where('id', ingredientId)
        .del();
  
      reply.status(204).send();
    },
  });

This is what my route handler looks like.

And this is my Sentry plugin init

import fp from 'fastify-plugin';

export default fp(async (fastify, opts) => {
  if (process.env.NODE_ENV === 'production') {
    fastify.register(require('fastify-sentry'), {
      dsn: process.env.SENTRY_DSN,
      environment: process.env.NODE_ENV,
      release: '1.0.0',
    });
  }
});

dnlup commented

Hi @MattJustMatt , thank you for opening this. It looks like the fallback error handler is used in the response (even though the status code should be different). I am going to take a look at it. Just a question, are you registering the plugin in your app.ts file?

dnlup commented

Also, maybe this could give some context: fastify/fastify#4501

dnlup commented

I see in you error handler you respond only in a production env

fastify.setErrorHandler((error, request, reply) => {

    if ((process.env.NODE_ENV || 'development') === 'production') {
      reply.status(500).send({ message: "Internal Server Error"});`

what do you do if you are on a development environment?

dnlup commented

I couldn't reproduce with this minimal example:

const fastify = require('fastify')
const plugin = require('.')

const env = process.env.NODE_ENV

const app = fastify({
  logger: true
})
app.register(plugin)
app.setErrorHandler((error, request, reply) => {
  if (env === 'production') {
    reply.status(500).send({ message: 'redacted' })
  } else {
    reply.status(500).send({ message: error.message }) 
  }
})
app.get('/', async () => {
  throw new Error('test')
})

app.listen({ port: 4000 })

Note how the error handler called is the plugin one due to the encapsulation feature of fastify 4.
Screenshot 2023-07-18 alle 09 18 51

dnlup commented

I couldn't reproduce this issue, feel free to reopen it if it still persists