method of preventing process blocking caused by errors in Node.js _node.js

Source: Internet
Author: User
Tags error handling

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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.