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.
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)
An alternative to listening to 'after'
is listening to 'restifyError'
:
server.on('restifyError', (req, res, err, cb) => {
req.log.error(err)
return cb();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With