如何获取(处理)错误(不可接受和内部服务器错误)Ajax中的异常内容



>我在服务器端添加了内部错误(抛出异常(。现在我想在客户端处理此错误。但是,我得到的错误内容未定义。

我正在使用邮递员,看到我的响应是 JSON 格式,它具有"消息"之类的响应参数。我试图解析JSON,再次得到Cannot read property 'Message' of undefined

Ajax 函数定义如下:

function Ajax(url, method,  json, successFunction, errorFunction, skipErrorDlg) {
$.ajax({
    url: url,
    data: json,
    type: method,
    contentType: 'application/json',
    beforeSend: function (xhr) {
        xhr.setRequestHeader('Authorization', GlobalAuthToken);
    },
    processData: false,
    dataType: 'json',
    success: function (data) {
        successFunction(data);
    },
    error: function(event, jqxhr, settings, thrownError) {
        if (errorFunction != null) {
            errorFunction();
        }
    }
});

}

我在代码中使用了这个函数,错误部分像这样,在这个函数中如何获取异常内容?

function(event, jqxhr, settings, thrownError)
            {           
                alert("ERROR HAPPENED");
                var responseString = JSON.stringify(event);
                alert(responseString.Message);
                alert("event" + event.Message);
            },

邮递员结果:

{
"Message": "Please select corresponding template."}

预期结果应为: Please select corresponding template.

我解决了这个问题,如果你遇到这种问题,试试这样:

function showAjaxError(event, jqxhr, settings, thrownError) {
    var msg = "";
    if (event.hasOwnProperty('responseJSON')) {
        var resp = event['responseJSON'];
        msg = (resp && resp.hasOwnProperty('Message')) ? resp.Message : "";
        msg = msg + ((resp && resp.hasOwnProperty('ExceptionMessage')) ? "nn" + resp.ExceptionMessage : "");
        if (resp && resp.hasOwnProperty('InnerException')) {
            msg = msg + ((resp && resp.InnerException.hasOwnProperty('ExceptionMessage')) ? "nn" + resp.InnerException.ExceptionMessage : "");
        }
    } else {
        msg = event.responseText;
    }
}

最新更新