简体   繁体   中英

How to handle unhandled exceptions in node.js

In my project I am trying to catch exception while opening connection using mongoose.createConnection , what to do when getting an error on this code:

var createdDb = mongoose.createConnection(connectionString);
createdDb.on("error", function (err) {
    console.error("Error connecting to Mongo", err);
});

But my question is in general - how can I catch ANY uncaught exception, and show the error (as a simple string)? I have this code in app.js, but it doesn't seem exceptions are getting there:

app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});
process.on('uncaughtException', function(err) {
  console.log('Caught exception: ' + err);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM