Node's asynchronous nature is its greatest charm, but it brings convenience but also brings a lot of trouble and pits, error capture is one. Because of the asynchronous nature of Node, we cannot use Try/catch to catch exceptions in callback functions, such as:
try {
console.log (' Enter Try/catch ');
Require (' FS '). Stat (' some_file_does_not_exist ',
function readcallback (err, content) {
if (err) {
throw Err Throw exception
}}
);
catch (E) {
//is not capturing the exception thrown in the Readcallback function
} finally {
console.log (' Leave Try/catch ');
}
The results of the operation are:
Enter Try/catch
leave Try/catch
test.js:7
throw err;//Throw exception
^
error:enoent, stat ' Some_file_does_ Not_exist '
The above code causes Readcallback to throw an exception because fs.stat to query the state of a nonexistent file. Because of the asynchronous nature of the Fs.read, the call to the Readcallback function occurs after the Try/catch block ends, so the exception is not captured by Try/catch. Node then triggers the Uncaughtexception event, and if the event is still not responding, the entire process is crash.
Programmers will never be able to guarantee that there is no uncaughtexception in the code, even if their own code is careful enough to write, there is no guarantee that the Third-party module is not a bug, for example:
var deserialize = require (' deserialize ');
Suppose deserialize is a third-party module with Bugs
//app is a express service object
app.get ('/users ', function (req, res) {
mysql.query (' SELECT * from user WHERE id=1 ', function (err, user) {
var config = deserialize (user.config);
If this triggers the deserialize bug
res.send (config);});
If the bug in the deserialize module is unfortunately triggered, an exception is thrown here, and the end result is the entire service crash.
When this happens on a Web service, the result is catastrophic. A uncaughtexception error can cause all current user connections to be disconnected and cannot even return a normal HTTP error code, and the user can wait until the browser times out to see a no data received error.
This is a very brutal and rude exception handling mechanism, and no online service should cause the server to crash because of Uncaughtexception. A friendly error-handling mechanism should meet three conditions:
Returns a 500 page for the user who raised the exception
Other users are unaffected and can be accessed normally
does not affect the normal operation of the entire process
It is regrettable that it is impossible to ensure that uncaughtexception does not affect the healthy functioning of the whole process. When node throws a Uncaughtexception exception, the stack of the current environment is lost, causing node to fail to reclaim memory properly. That is, every time a uncaughtexception can cause a memory leak.
That being the case, the second thing we can do is to exit the process to restart the service, if the first two conditions are met.