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 allows for exception capture and allows code to continue:
For example:
When the function throws an error, the code stops executing:
(function () {
var a = 0;
A ();
Console.log ("Get here."); Do not execute
}) ();
After you use Try-catch for error handling, your 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);
});
The above is a small set to introduce the node.js to prevent errors caused by the process of blocking the method, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!