簡體   English   中英

Catch語句未捕獲引發的錯誤

[英]Catch statement does not catch thrown error

由於某種原因,此代碼給了我一個未捕獲的異常錯誤。 似乎catch塊未捕獲錯誤。 嘗試catch塊的作用域是否使我不能在嵌套函數中引發錯誤,然后期望它被鏈上較高范圍的catch語句捕獲? 我正在使用的應用程序中的一些敏感數據已被刪除,但是它期望leadInfo [0/1]是從URL參數提取的32個字符的字母數字字符串。

這里的根本問題是我的AJAX調用從API返回了一個錯誤,並且該錯誤未在應用程序中正確處理。 因此,需要throw語句。 AJAX調用可以很好地完成,並返回一個不包含電子郵件地址作為屬性的JSON對象,因此我需要以更改頁面的方式來處理該問題。

    jQuery(document).ready(function(){
        try {
            url = "http://api.com/api/v1/lead/" + leadInfo[1]

            jQuery.ajax({
                type: 'GET',
                contentType: 'application/json',
                url: url,
                dataType : 'jsonp',
                success: function (result) {

                    result = jQuery.parseJSON(result);

                    if(!result.data.email){
                        throw ('New exception');
                    }
                    console.log(result);
                    jQuery('.email').html(result.data.email);
                }
            });


            jQuery('.surveryButton').click(function(){
                window.location.replace("http://" + pgInventory.host + pgInventory.path + leadInfo[0] + "&curLeadId=" + leadInfo[1] + "&curViewedPages=0");
            });
        }
        catch(err) {
            jQuery('.email').html('your e-mail address');
            jQuery('#arrowContent').remove();
        }
});

您的try catch塊失敗的原因是因為ajax請求是異步的。 try catch塊將在Ajax調用之前執行並發送請求本身,但是在返回結果時,將在稍后時拋出錯誤。

執行try catch塊時,沒有錯誤。 引發錯誤時,沒有try catch 如果您需要對ajax請求進行try catch ,請始終將ajax try catch塊放在success回調中,切勿在其之外。

這是您應該如何做:

success: function (result) {
    try {
      result = jQuery.parseJSON(result);

      if (!result.data.email) {
         throw ('New exception');
      }
      console.log(result);
      jQuery('.email').html(result.data.email);
    } catch (exception) {
      console.error("bla");
    };
}

問題在於,ajax從定義上講是異步的。 您的異常不會從$.ajax函數內引發,而是在成功時從回調函數引發(稍后觸發)。

您還應該給它一個error: function(data) {}參數,以處理服務器響應錯誤,此外,您還應該將try / catch塊放在回調函數中。

如果您真的想在回調之外捕獲它,則應該考慮調用一個函數而不是引發異常,因為我不知道如何實現。

由於javascript中回調方法的異步性質,引發錯誤的函數上下文與原始函數不同。 您應該這樣做:

success: function (result) {
  try {
    result = jQuery.parseJSON(result);
    if(!result.data.email){
      throw ('New exception');
    }
    console.log(result);
    jQuery('.email').html(result.data.email);
  }
  catch(err) {
    // Dealing with the error
  }
}

我建議您看一下這篇有關(非常特殊的) 上下文 ,Java語言中的閉包綁定的出色文章

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM