Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle (i.e. log) errors in restify

In our restify app, when we pass an error to next, a generic 500 error is returned, which is all just fine. However, I need to also log the details of the error somewhere so that I know what happened.

Previously, I worked on an express application, and a centralized error-handling middleware gave us the ability to do any arbitrary code when receiving errors, like logging.

What's the "restify way" to centralizing the logging of error details? I do not want to sprinkle logging statements throughout the entire app.

like image 501
Jacob Avatar asked Mar 16 '23 21:03

Jacob


2 Answers

A Restify server object emits an 'after' event once all other route handlers are done for a request. You can put your logging code in an 'after' event handler:

var svr = restify.createServer()
  .get('/hello-world', hello_world_hndlr)
  .on('after', function (req, resp, route, err) {
    // logging here
  })
  .listen(SVR_PORT)
like image 149
user2524973 Avatar answered Mar 28 '23 12:03

user2524973


An alternative to listening to 'after' is listening to 'restifyError':

server.on('restifyError', (req, res, err, cb) => {
  req.log.error(err)
  return cb();
});
like image 32
c24w Avatar answered Mar 28 '23 10:03

c24w