我有一个Node.js应用程序来进行一些简单的处理,但是,每次出现错误时,服务器都会崩溃。
2011-12-19T19:27:49+00:00 app[web.1]: node.js:134
2011-12-19T19:27:49+00:00 app[web.1]: throw e; // process.nextTick error, or 'error' event on first tick
2011-12-19T19:27:49+00:00 app[web.1]: ^
2011-12-19T19:27:49+00:00 app[web.1]: TypeError: Object { customer_id: 4eef8ddb74019b9d4f00001d,
2011-12-19T19:27:49+00:00 app[web.1]: date: Mon, 19 Dec 2011 19:27:36 GMT,
2011-12-19T19:27:49+00:00 app[web.1]: callsid: '123',
2011-12-19T19:27:49+00:00 app[web.1]: _id: 4eef902887e9770100000008 } has no method 'save'
2011-12-19T19:27:49+00:00 app[web.1]: at Promise.<anonymous> (/app/src/call.js:137:24)
2011-12-19T19:27:49+00:00 app[web.1]: at Promise.<anonymous> (/app/node_modules/mongoose/lib/promise.js:120:8)
2011-12-19T19:27:49+00:00 app[web.1]: at Promise.<anonymous> (events.js:64:17)
2011-12-19T19:27:49+00:00 app[web.1]: at Promise.emit (/app/node_modules/mongoose/lib/promise.js:59:38)
2011-12-19T19:27:49+00:00 app[web.1]: at Promise.complete (/app/node_modules/mongoose/lib/promise.js:70:20)
2011-12-19T19:27:49+00:00 app[web.1]: at /app/node_modules/mongoose/lib/query.js:738:28
2011-12-19T19:27:49+00:00 app[web.1]: at model.init (/app/node_modules/mongoose/lib/model.js:181:36)
2011-12-19T19:27:49+00:00 app[web.1]: at cb (/app/node_modules/mongoose/lib/query.js:736:14)
2011-12-19T19:27:49+00:00 app[web.1]: at Array.<anonymous> (/app/node_modules/mongoose/lib/utils.js:394:16)
2011-12-19T19:27:49+00:00 app[web.1]: at model.<anonymous> (/app/node_modules/mongoose/lib/document.js:181:5)
如何防止此类错误?例如,当我调用一个不存在的变量时,服务器崩溃了。我理解错误,但有时我只注意到部署时的错误,服务器崩溃。
答案 0 :(得分:2)
您可以通过使用process.on('uncaughtException', callback)
捕获'uncaughtException'来确保您的脚本不会停止,如下所示:
process.on('uncaughtException', function (exception) {
// handle or ignore error
console.log(exception);
});
setInterval(function() {
console.log('tick, even after error');
}, 1000);
a += 1;