使node.js不会因错误而退出 [英] Make node.js not exit on error
问题描述
我正在使用Socket.IO在面向Websocket的node.js服务器上工作.我注意到一个错误,其中某些浏览器未遵循与服务器的正确连接过程,并且未编写代码来妥善处理该错误,总之,它调用了一个从未设置的对象的方法,从而杀死了该对象服务器由于错误.
I am working on a websocket oriented node.js server using Socket.IO. I noticed a bug where certain browsers aren't following the correct connect procedure to the server, and the code isn't written to gracefully handle it, and in short, it calls a method to an object that was never set up, thus killing the server due to an error.
我特别关注的不是错误,而是当发生此类错误时,整个服务器都将关闭.我可以在节点的全局级别上做任何事情来做到这一点,以便如果发生错误,它只会记录一条消息,也许会杀死该事件,但是服务器进程将继续运行?
My concern isn't with the bug in particular, but the fact that when such errors occur, the entire server goes down. Is there anything I can do on a global level in node to make it so if an error occurs it will simply log a message, perhaps kill the event, but the server process will keep on running?
我不希望其他用户的连接断开,因为一个聪明的用户在包含的大型代码库中利用了未捕获的错误.
I don't want other users' connections to go down due to one clever user exploiting an uncaught error in a large included codebase.
推荐答案
您可以将侦听器附加到流程对象的uncaughtException
事件.
You can attach a listener to the uncaughtException
event of the process object.
代码取自实际的 Node.js API参考(这是过程"下的第二项"):
Code taken from the actual Node.js API reference (it's the second item under "process"):
process.on('uncaughtException', function (err) {
console.log('Caught exception: ', err);
});
setTimeout(function () {
console.log('This will still run.');
}, 500);
// Intentionally cause an exception, but don't catch it.
nonexistentFunc();
console.log('This will not run.');
现在您要做的就是记录它或使用它做某事,以防万一,您知道在什么情况下会发生错误,应该在Socket.IO的GitHub页面上提交错误:
https://github.com/LearnBoost/Socket.IO-node/issues
All you've got to do now is to log it or do something with it, in case you know under what circumstances the bug occurs, you should file a bug over at Socket.IO's GitHub page:
https://github.com/LearnBoost/Socket.IO-node/issues
这篇关于使node.js不会因错误而退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!