Ways to prevent process blocking in Node.js errors _node.js

Source: Internet
Author: User
Tags error handling

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-catchAllow 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.

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.