简体   繁体   English

捕获块不捕获错误

[英]Catch block does not catch errors

I have this code and when I manipulate the try block so that there occur errors the catch block does not catch them (for example errors that the Facebook SDK throws). 我有这段代码,当我尝试使用try块时,会发生catch块无法捕获它们的错误(例如,Facebook SDK引发的错误)。 I am really new to using the try and catch structure and do not understand how I can handle the facebook errors. 我真的是使用try and catch结构的新手,并且不了解如何处理facebook错误。

try{

    window.fbAsyncInit = function() {
        FB.init({
          appId      : 'XXXXXXXXXXXX',
          xfbml      : true,
          version    : 'v2.7'
        });
        FB.AppEvents.logPageView();

    };

  (function(d, s, id){
     var js, fjs = d.getElementsByTagName(s)[0];
     if (d.getElementById(id)) {return;}
     js = d.createElement(s); js.id = id;
     js.src = $fbSource;  
     fjs.parentNode.insertBefore(js, fjs);
   }(document, 'script', 'facebook-jssdk'));

}catch(e){

    console.log('Error: '+e);

}

That's because the errors aren't being thrown when the try block is active. 这是因为try块处于活动状态时不会引发错误。 By the time the errors are being thrown (later, when Facebook calls your fbAsyncInit function), the code has long since exited the try block. 到抛出错误时(后来,当Facebook调用fbAsyncInit函数时),代码退出try块已经很久了。

If you want to catch those errors, you'll need a try block within your fbAsyncInit callback and/or to receive errors in the way the FB API indicates, since most async APIs can't (by nature) be compatible with try/catch . 如果您想捕获这些错误,则需要 fbAsyncInit回调中使用try块和/或以FB API指示的方式接收错误,因为大多数异步API(本质上)都无法与try/catch兼容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM