Nodejs Exception Handling Uncaughtexception article

Source: Internet
Author: User
Tags emit try catch

Nodejs Exception Handling Uncaughtexception article

Wang Yu-april 08, 2015

Many NodeJS developers complain about the trouble of handling the exception, and we'll comb through some of the columns to sort out the usual exception handling methods in NodeJS.
As with most programming languages, you can throw throw an exception in NodeJS:

    1. throw new Error(‘Catch me‘);

In order to catch this exception it is necessary to package the code in Try Catch :

    1. try{
    2. throw new Error(‘Catch me‘);
    3. }catch(e){
    4. // error captured
    5. }

However, because of the asynchronous nature of the NodeJS, the code above can be invalidated with a little modification:

  1. try{
  2. process.nextTick(function my_app(){
  3. throw new Error(‘Catch me‘);
  4. })
  5. }catch(e){
  6. // never called
  7. }

In the real world, exceptions are always generated in a module. The so-called module is a unit that can complete a function, even a simple function can be seen as a module. As the number of lines of project code increases, the complexity of asynchronous nesting increases, often with exceptions that are not captured. A NodeJS application that has no strong robustness will be suspended because of an uncaught exception, resulting in service unavailability. To change the perception that Nodejs is fragile, developers need to deepen their understanding of the language exception handling mechanism.

Uncaughtexception

uncaughtExceptionis actually an event of the NodeJS process. This event is triggered if an exception is generated in the process and not captured by any Try Catch . To simplify the problem, let's take a look at the case of synchronization.

  1. function external() {
  2. throw new Error(‘Catch me‘);
  3. }
  4. function internal() {
  5. external();
  6. }
  7. internal(); //error will be thrown

Execute the program on the command line, and the script will break on the line that throws the exception. Next, because there is no Try Catch , the exception will bubble up until the event loop, and Nodejs's default handling of the exception is simple, and the code is processed like this:

  1. function _MyFatalException(err){
  2. if(!process.emit(‘uncaughtException‘,err)){
  3. console.error(err.stack);
  4. process.emit(‘exit‘,1);
  5. }
  6. }

Nodejs default handling for uncaught exceptions is:-Trigger uncaughtException Event-if uncaughtexception is not listening, then-print exception stack information-triggers the exit event of the process

If you are using NodeJS to develop a server, then you certainly do not want an accidental exception to the entire server hanging out. So uncaughtException is it possible to stop the server's process from exiting as long as it listens? The answer is yes, but don't do it!. See this example:

  1. var express = require(‘express‘);
  2. function external(cb) {
  3. process.nextTick(function () {
  4. throw new Error();
  5. cb.call(null, ‘sunny‘);
  6. })
  7. }
  8. var app = express();
  9. app.get(‘/weather‘, function (req, res) {
  10. external(function (data) {
  11. res.end(‘Weather of Beijing is ‘ + data);
  12. })
  13. })
  14. app.listen(8018);
  15. function noop(){}
  16. process.on(‘uncaughtException‘, noop)

The above example assumes that when a user visits a site you can see the local weather and we use it apache2-utils to simulate the request

Ab-n 1000-c Http://localhost:8018/weather

Bad! The request has been waiting for the memory to rise. The reason is that it is res.end never executed, the existing I/O waiting state, the resources that have been opened not only will not be released, and the server is also tirelessly accepting new user requests.

Handling exceptions in NodeJS is expensive, and inadvertently causes memory leaks and applications to be in an unstable state. In order to improve robustness, we can use Cluster patterns, which are recommended by:-Return an error code for an exception request-the worker who made the error no longer accepts a new request-exits the worker process

The writer is ONEAPM engineer Wang Yu, want to read more good technical articles, please visit the ONEAPM Official technology blog.

Nodejs Exception Handling Uncaughtexception article

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.