Oscar Godson
Oscar Godson

Reputation: 32716

After res.send() event in Restify?

I'm trying to add Bugsnag to my Node Restify service. We have a ton of routes already and such so I'm trying not to add Bugsnag calls all over our code base and I'm also trying to do something global so there's never a mistake where a dev forgets to add the error reporting.

Conceptually I want after any res.send() to get the status code. If the statusCode is >=400 i want to notify Bugsnag by calling Bugsnag.notify. I already check for errors everywhere so no errors ever show up to the clients (browsers, phones, etc) but they do get sent, for example, res.send(401, { message: 'You dont have permission to do that' }) which I'd like to be able to hook into and pass who tried to do that, what route, etc. Problem is I can't get the after event to fire at all:

server.on('after', function (req, res, route, error) {
  console.log('AFTER')
});

I think I misunderstand what after is for. It's at the top of my index.js before any routes or other middleware (server.use) is defined.

My general code structure looks something like:

  server.post('/foo', function (req, res, next) {
    FooPolicy.create(req, function (err) {
      if (err) return res.send(err.code, err.data);
      FooController.create(req.params, function (response) {
        res.send(response.code, response.data)
        next();
      });
    });
  });

FooPolicy == checking permissions
FooController == actually creating the model/data

Upvotes: 2

Views: 1394

Answers (1)

gerrard00
gerrard00

Reputation: 1738

The issue is that the after event is currently treated like any other handler. That means that if you don't call next in every code path, the after event will never be emitted.

In the meantime, adding a next call will cause your after event handler to fire.

if (err) {
  res.send(err.code, err.data);
  next();
  return;
}

Upvotes: 1

Related Questions