陷阱函数未定义Javascript和jQuery中的错误

时间:2011-12-22 13:58:17

标签: javascript jquery error-handling

好的,我确实使用firebug来确定Dev中没有定义函数的时间。我想在制作中做的是显示一个模态窗口,说明已收到错误,然后在点击时将它们重定向到另一个页面。不那么容易。

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

我正在使用.ajaxSetup来设置将运行asynch的几个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调用都需要。

3 个答案:

答案 0 :(得分:3)

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

你应该在success方法中尝试/捕获。

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

答案 1 :(得分:2)

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

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

答案 2 :(得分:1)

好吧,错误实际发生在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
});