Exceptions thrown in asynchronous javascript not caught

孤街醉人 提交于 2021-02-07 05:39:21

问题


Basically, why isn't this exception caught?

var http = require('http'),
    options = {
      host: 'www.crash-boom-bang-please.com',
      port: 80,
      method: 'GET'
    };

try {
  var req = http.request(options, function(res) {
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
      console.log('BODY: ' + chunk);
    });
  });

  req.on('error', function(e) {
    throw new Error("Oh noes");
  });
  req.end();
} catch(_error) {
  console.log("Caught the error");
}

Some people suggest that these errors need to be handled with event emitters or callback(err) (having callbacks with err, data signature isn't something I'm used to)

What's the best way to go about it?


回答1:


When you are throwing the error the try {} block has been long left, as the callback is invoked asynchronously outside of the try/catch. So you cannot catch it.

Do whatever you want to do in case of an error inside the error callback function.




回答2:


As of node version 0.8 you can constrain exceptions to domains. You can constrain exceptions to a certain domain and catch them at that scope

If you're interested, I've written a small function that catches asynchronous exceptions here: Javascript Asynchronous Exception Handling with node.js. I'd love some feedback This will let you perform the following:

var http = require('http'),
    options = {
      host: 'www.crash-boom-bang-please.com',
      port: 80,
      method: 'GET'
    };

atry(function(){
  var req = http.request(options, function(res) {
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
      console.log('BODY: ' + chunk);
    });
  });

  req.on('error', function(e) {
    throw new Error("Oh noes");
  });
  req.end();
}).catch(function(_error) {
  console.log("Caught the error");
});



回答3:


Javascript doesn't have just function scope, try-catch also is block scoped. That is the reason.



来源:https://stackoverflow.com/questions/10823205/exceptions-thrown-in-asynchronous-javascript-not-caught

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!