如何处理node.js中的所有异常 [英] How to handle all exceptions in node.js

查看:110
本文介绍了如何处理node.js中的所有异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用node.js工作了几周之后,我发现node.js服务器错误和PHP之类的常规服务器端语言有所不同。

After working for a couple of weeks with node.js, I found that there is a difference between node.js server errors and regular server side languages like PHP.

一个简单的例子:如果我们的网站出现任何错误。

A simple example: IF an error happens in our website for ANY reason.



如果用户向服务器和MySQL发送一些无效数据,MySQL将向该特定用户输出错误,整个应用程序将不会关闭。

in PHP
If a user send some invalid data to server and MySQL, MySQL will output error to that specific user and the whole application won't go down.

在Nodejs

如果用户向服务器和MySQL发送一些无效数据,那么nodejs Server将会关闭,因此所有用户将断开连接,并且没有

in Nodejs
If a user send some invalid data to server and MySQL, nodejs Server will go down and so all the users will disconnect and there is no connection between users anymore.

这是一个很大的问题。在大型Web应用程序中,不可能处理所有错误以避免Nodejs服务器停机,问题是,

是否有任何方法来处理任何未知的致命错误和异常输出或类似的东西。

This is a really big problem. in large web applications, It is impossible to handle all errors to avoid Nodejs server to go down, and the question is,
Is there any way to handle any unknown fatal errors and exceptions to a specific output or something like it.

推荐答案

您可以使用 uncaughtException 事件在进程对象上做你想要的,但是像其他人一样说,建议使用正确级别的域和捕获/处理错误。

You can use the uncaughtException event on the process object to do what you want, but like others have said, domains and catching/handling errors at the correct level is recommended.

process.on('uncaughtException', function(err) {
  console.log('Caught exception: ' + err);
});

这篇关于如何处理node.js中的所有异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆