未捕获异步javascript中引发的异常 [英] Exceptions thrown in asynchronous javascript not caught

查看:78
本文介绍了未捕获异步javascript中引发的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,为什么没有捕获到此异常?

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

有人建议这些错误需要通过事件发射器或callback(err)处理(对于带有err的回调,我不习惯使用数据签名)

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)

最好的方法是什么?

推荐答案

抛出错误时, try {} 块已经很久了,因为回调是在try之外异步调用的./抓住.所以你抓不到它.

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.

这篇关于未捕获异步javascript中引发的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆