【问题标题】:Trapping Function not defined error in Javascript and jQuery在 Javascript 和 jQuery 中捕获函数未定义错误
【发布时间】:2012-01-26 03:45:25
【问题描述】:

好的,我确实使用 firebug 来确定何时未在 Dev 中定义函数。我想在生产中做的是显示一个模式窗口,说收到了一个错误,然后在点击时将它们重定向到另一个页面。没那么容易。

请理解此功能确实有效,并且被调用的组件有效。我将故意拼错函数调用,以演示我没有通过 jquery ajax 函数收到的错误。

我正在使用 .ajaxSetup 为几个将运行异步的 ajax 函数设置默认选项:

$.ajaxSetup({
    type: "POST",
    dataType: "json",
    url: "DMF.cfc",
    data: {
    qID: 1,
    returnFormat: "json"
    },
    beforeSend: function() {
        $('#loadingmessage').fadeIn();  // show the loading message.
    },
    complete: function() {
        $('#loadingmessage').fadeOut();  // show the loading message.
    }
    });  //end AjaxSetup

实际的ajax调用是:

$.ajax({
        data: {
            method: 'getCurrentIssues'
        },
        success: function(response) {
            nsNewDebtshowDebtIssues(response);
        },//end success function
        error: function(jqXHR, exception) {
            alert("Error running nsNewDebt.showDebtIssues");
        }
    })  //end getCurrentIssues Ajax Call

我强制的错误是success函数中运行的方法实际上应该是nsNewDebt.showDebtIssues。 Firebug 在控制台中正确显示错误 nsNewDebtshowDebtIssues 未定义,但 ajax 调用的实际错误消息未运行,因此如果最终用户正在运行该页面,它会显示该页面已挂起。

所以,总而言之,我想知道如何跟踪发生此类错误的时间,最好将其放置在 .ajaxSsetup 的错误部分中,但如果在每个 .ajax 调用中都有必要。

【问题讨论】:

  • 将代码封装在try { ... } catch(err) { ... } 块中的“成功”函数中怎么样?

标签: javascript jquery error-handling


【解决方案1】:

这不是 ajax 错误,因此您无法通过 ajaxError 方法处理它。

你应该在success方法中做一个try/catch。

success: function(response) {
    try {
        nsNewDebtshowDebtIssues(response);
    } catch (ex) {
        //exception occured
        //alert("Error running nsNewDebt.showDebtIssues");
        alert( ex.message + '\n\tin file : ' + ex.fileName + '\n\t at line : ' + ex.lineNumber);
    }
}

【讨论】:

    【解决方案2】:

    在拨打电话之前,您可以:

    if(typeof nsNewDebtshowDebtIssues == 'function') {
      // .. call it ..
    }
    

    【讨论】:

      【解决方案3】:

      嗯,错误实际上是在 AJAX 调用成功之后发生的(因为它来自您的success 处理程序),所以error 处理程序确实不会被调用。

      如果您想对实际的 AJAX 请求错误和源自 success 处理程序的更多错误使用相同的处理程序,您可以定义一个命名函数并将其用作您的 error 处理程序和来自 try /catch 块在您的 success 处理程序中:

      function handleError(jqXHR, status, exception)
      {
          alert("Error running request.");
          // Or print something from 'jqXHR', 'status' and 'exception'...
      }
      
      $.ajax({
          data: {
              method: "getCurrentIssues"
          },
          success: function(response, status, jqXHR) {
              try {
                  nsNewDebtshowDebtIssues(response);
              } catch (x) {
                  handleError(jqXHR, status, x);
              }
          },
          error: handleError
      });
      

      【讨论】:

      • 绝对是最灵活的解决方案,尽管它们都没有错。这考虑到我希望有一个错误函数来统治它们。谢谢大家。
      猜你喜欢
      • 1970-01-01
      • 2016-02-17
      • 1970-01-01
      • 2014-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多