Node.js服务器崩溃没有错误信息
我有一个Node.js服务器不断崩溃,没有logging任何forms的错误信息。 这是一个典型的情况? 如何捕获错误并在崩溃之前将其logging下来?
在设置服务器的侦听器之前,一个好的开始就是设置,特别是在生产环境中,一个logging细节exception的处理程序。 看看这里 :
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(); // ... app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); // then, set the listener and do your stuff...
要完成@matteofigus答案,您还可以听取未处理的诺言拒绝 。
process.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`
您可以使用名为“errorhandler”的中间件和“logger”(log4js-npm-package),您可以logging所有错误exception。 以下是Errorhandler的代码:
//中间件:Catch-Allerror handling程序。 以便我们logging错误,但不要将内部错误细节泄露给客户端。
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; }
节点v6.11.0,Windows 10。
尝试了其他build议在这里无济于事 – 应用程序只是停止,甚至没有错误使用
process.on('uncaughtException',...) process.on('unhandledRejection',....)
最后跟踪退出/崩溃到一个recursion函数调用。 下面的代码演示了这个问题。
"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"); } }
再没有什么 – 只是停下来。
解决方法(无需重新devise代码)是使用setImmediate(以避免recursion过程);
function recursiveFunction(){ console.log(count++); setImmediate(recursiveFunction); }
(我最终按Ctrl-c这个来阻止它。)
在节点github问题上报告