Search code examples
node.jsrestify

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.


Solution

  • 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)