Objective
In Node.js, when a callback function is wrong, the entire process crashes, affecting subsequent code execution.
Node.js does this because the state of the process is indeterminate when an unhandled error occurs. After that, it will not work properly. If the error is always not handled, it will always throw unexpected errors, which is not conducive to debugging.
There are two main ways to prevent process blocking caused by errors:
I. Try-catch
try-catch
Allow for exception capture and keep code going:
For example:
When the function throws an error, the code stops executing:
(function () {
var a = 0;
A ();
Console.log ("Get here."); Do not execute
}) ();
With try-catch
error handling, the code can continue to execute:
(function () {
var a = 0;
try {
a ();
} catch (e) {
console.log (e);
}
Console.log ("Get here."); Get here.
}) ();
Try-catch cannot capture future execution function errors
It is not possible to catch errors thrown by functions that are executed in the future. This throws an unhandled exception directly, and the catch
code block is never executed:
try {
settimeout (function () {
throw new Error ("here");
},
catch (E) {
console.log (e)
}
This is why in Node.js, every step of the bean sprouts is correctly handled incorrectly.
Add Uncatchexception Processor
If you add a uncatchException
processor, the process does not exit when the function throws an error.
Process.on ("Uncatchexception", function (e) {
console.log (e);
Process.exit (1);
});
Summarize
The above is to prevent node.js in the process of blocking the whole content of the method, I hope to use Node.js to help.