Exceptions thrown in asynchronous javascript not caught

前端 未结 3 2617
一整个雨季
一整个雨季 2021-02-20 17:46

Basically, why isn\'t this exception caught?

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


        
3条回答
  •  青春惊慌失措
    2021-02-20 18:31

    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");
    });
    

提交回复
热议问题