Preface
In Node.js, when an error occurs in a callback function, the entire process will crash, affecting the execution of subsequent code.
Node.js handles this way because when an uncaught error occurs, the status of the process is uncertain. It won't work properly after that. If the error is never processed, unexpected errors will be thrown, which is not conducive to debugging.
There are two main ways to prevent process blocking caused by errors:
1. try-catch
try-catch allows exception capture and allows the code to continue execution:
For example:
When the function throws an error, the code stops executing:
(function() { var a = 0; a(); console.log("get here."); // Not executed})(); After using try-catch for error processing, the code can still be executed:
(function() { var a = 0; try { a(); } catch (e) { console.log(e); } console.log("get here."); // get here.})();try-catch cannot catch future execution function errors
It is impossible to capture errors thrown by functions that are only executed in the future. This will throw an uncaught exception directly, and catch code block will never be executed:
try { setTimeout(function() { throw new Error("here"); }, 10);} catch(e) { console.log(e);}This is why in Node.js, bean sprouts are correctly handled at each step.
Add uncatchException handler
If an uncatchException processor is added, the process will not exit when the function throws an error.
process.on("uncatchException", function(e) { console.log(e); process.exit(1);});Summarize
The above is all the ways to prevent process blocking by errors in Node.js. I hope it will be helpful to everyone using Node.js.