我有一个Node.js服务器,它经常在没有记录任何错误信息的情况下崩溃。这是一种典型情况吗?我该如何捕获错误并在崩溃前记录它?
我有一个Node.js服务器,它经常在没有记录任何错误信息的情况下崩溃。这是一种典型情况吗?我该如何捕获错误并在崩溃前记录它?
在设置服务器监听器之前,尤其是在生产环境中,建议首先设置一个异常处理程序来记录详细信息。请参考这里:
process.on('uncaughtException', function (exception) {
console.log(exception); // to see your exception details in the console
// if you are on production, maybe you can send the exception details to your
// email as well ?
});
如果您正在使用Express.js,请查看此处了解如何查看完整的错误堆栈(如果您在生产环境中,可以将其发送到电子邮件中)。
在这种情况下,在实例化侦听器之前告诉它给您完整的细节。var express = require('express');
// ...
var app = express();
var errorHandler = require('errorhandler')
// ...
app.use(errorHandler({ dumpExceptions: true, showStack: true }));
// then, set the listener and do your stuff...
2019更新:您需要安装errorHandler包
errorHandler
中间件不再与 Express 捆绑在一起。您可以通过运行 npm install errorhandler
来安装它。有关详情,请参见此处 https://github.com/expressjs/errorhandler。 - muchwebprocess.on('unhandledRejection', (reason, p) => {
console.log("Unhandled Rejection at: Promise ", p, " reason: ", reason);
// application specific logging, throwing an error, or other logic here
});
somePromise.then((res) => {
return reportToUser(JSON.pasre(res)); // note the typo (`pasre`)
}); // no `.catch` or `.then`
writeFileSync("./foo.json", "…")
,这通常是可以的,但由于我正在使用PM2“监视”服务器目录以检测文件更改,也就是说,每当服务器目录中的文件更改时,PM2都会重新启动服务器,因此这导致了服务器“崩溃”。我通过为.data
文件夹添加watch_ignore
配置并将foo.json
放在其中解决了这个问题。Node v6.11.0,Windows 10。
尝试了这里的其他建议,但都无济于事 - 应用程序只是停止了,甚至没有错误信息
process.on('uncaughtException',...)
process.on('unhandledRejection',....)
"use strict" ;
process.on('uncaughtException', function (exception) {
console.log(exception);
});
var count = 0 ;
function recursiveFunction(){
console.log(count++);
recursiveFunction();
}
recursiveFunction() ;
function recursiveFunction(){
console.log(count++);
try{
recursiveFunction();
}
catch(e){
console.log("recursion error");
}
}
再次发生了停止情况,没有任何错误信息。
一个解决方法(无需重新设计代码)是使用setImmediate(避免递归过程);
function recursiveFunction(){
console.log(count++);
setImmediate(recursiveFunction);
}
最终我使用Ctrl+C停止了它。
在Node.js的GitHub问题页面上报告了此问题。
app.use(errorHandler);
function errorHandler(err, req, res, next) {
// XHR Request?
if (req.xhr) {
logger.error(err);
res.status(500).send({ error: 'Internal Error Occured.' });
return;
}
// Not a XHR Request.
logger.error(err);
res.status(500);
res.render('framework/error', { error: "Internal Server Error." });
// Note: No need to call next() as the buck stops here.
return;
}