Monday 23 January 2017

How to send an HTTP response (for example using Express), when a "unhandledRejection" promise error occures?

I'm quite new to Node and I'm currently developing a project using Express.I have to admit I find it very hard to setup error management!Let's say that, during an HTTP request, an error occures inside a Promise (who doesn't make errors?) and the error is not handled properly in the catch block (or a new Error occures in the catch block!).It seems that the mecanism provided by Node to deal with this situation is to add a unhandledRejection global handler:process.on('unhandledRejection', handle(reason, p) { // log the error }); But, in this global handler, we do not have access to the Express's response object so we can't send a 500 error to the client! The request will hangs until it timeouts...The only suggestion I've seen to deal with this is from this thread:app.use(function (req, res, next) { var l = process.on('unhandledRejection', function(reason, p) { console.log("Unhandled Rejection:", reason.stack); res.status(500).send('Unknown Error'); //next(reason); }); next(); process.removeEventLister('unhandledRejection', l); }); What do you think about this solution? Do some of you actually use something similar in production?Otherwise, how do you deal with unhandled promise rejections in your applications?

Submitted January 24, 2017 at 02:05AM by electrotype

No comments:

Post a Comment