Jquery 捕获$.ajax响应中的错误,并显示异常

Jquery 捕获$.ajax响应中的错误,并显示异常,jquery,json,ajax,Jquery,Json,Ajax,我有以下调用API并缓存结果的代码(因此可以多次使用): 有时,API会抛出异常,我正试图捕获并显示该异常。根据Firefox调试器,当发生异常时,响应数据如下所示: { "Message":"An error has occurred.", "ExceptionMessage":"Invalid object name 'Foo_Bar'.", "ExceptionType":"System.Data.SqlClient.SqlException", } 从中,我看到$.a

我有以下调用API并缓存结果的代码(因此可以多次使用):

有时,API会抛出异常,我正试图捕获并显示该异常。根据Firefox调试器,当发生异常时,响应数据如下所示:

{
   "Message":"An error has occurred.",
   "ExceptionMessage":"Invalid object name 'Foo_Bar'.",
   "ExceptionType":"System.Data.SqlClient.SqlException",
}
从中,我看到
$.ajax
中有一个
statusCode
对象,但我无法成功实现它。已关闭,但实际上无法检索异常消息

从今天的各种搜索中,我了解到了这一点,但是JSON没有解析,我不知道问题出在哪里,因为JSON在其他地方使用时可以解析:

function LoadDataFromApi(apiUrl) {
    if (!requestCache[apiUrl]) {
        requestCache[apiUrl] = $.ajax({
            type: 'GET',
            url: apiUrl,
            dataType: "json",
            statusCode: {
                500: function (json) {
                    var j = JSON.parse(json);
                    alert(j.Message);
                }
            }
        });
    }
    return requestCache[apiUrl];
}
如果有人能在我的代码中发现这个问题,我将不胜感激。

我们能看一下吗

public class theException
{
    public string Message { get; set; }
    public string ExceptionMessage { get; set; }
    public string ExceptionType { get; set; }
}

public class EvilDrController : ApiController
{
    public theException GetContrivedException()
    {
        var exception = new theException
        {
            ExceptionMessage = "Invalid object name 'Foo_Bar'.",
            ExceptionType = "System.Data.SqlClient.SqlException",
            Message = "An error has occured"
        };
        return exception;
    }
}
html文件或cshtml

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>EvilDr</title>
</head>
<body>

    <div>
        <h2>Parse JSON</h2>
    </div>
    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
    <script>
        //or whatever uri you want
        var uri = 'api/evildr';

        $(document).ready(function () {
            // Send an AJAX request
            $.getJSON(uri)
                .done(function (data) {
                    var j = JSON.stringify(data)
                    alert(j)
                });
        });
    </script>
</body>
</html>

邪恶博士
解析JSON
//或者任何你想要的uri
var uri='api/evildr';
$(文档).ready(函数(){
//发送AJAX请求
$.getJSON(uri)
.完成(功能(数据){
var j=JSON.stringify(数据)
警报(j)
});
});

多亏了我的帮助,经过多次搜索,我终于找到了答案

问题就在这里:

500: function (json) {
结果表明,尽管API返回JSON数据,但JQuery将其封装在一个包含许多属性的函数中

我所期望的JSON数据包含在jqXHR对象的
responseText
属性中,因此首先需要对其进行解析。因此,完整的解决方案是:

function LoadDataFromApi(apiUrl) {
    if (!requestCache[apiUrl]) {
        var result = $.ajax({
            type: 'GET',
            url: apiUrl,
            dataType: "json",
            statusCode: {
                // JQuery now has an jqXHR containing all the data we need regarding any success/failures (as we can address multiple status codes here)
                500: function (xhr) {
                    // Parse the JSON data we expected
                    var err = JSON.parse(xhr.responseText);
                    // Display the error data
                    console.log('Message:' + err.Message);
                    console.log('ExceptionMessage:' + err.ExceptionMessage);
                    console.log('ExceptionType:' + err.ExceptionType);
                },
                200: function (xhr) {
                    // console.log('success');
                    // var goodData = JSON.parse(xhr.responseText);
                }
            }
        });
        // This line would generally go in success, but I need to re-use the data regardless of the status code
        requestCache[apiUrl] = result;
    }
    return requestCache[apiUrl];
}

当API返回错误JSON时,它返回的HTTP状态码是什么?200行吗?或500服务器错误或其他一些状态代码?如果它返回HTTP 200 OK,但带有“错误”JSON负载,那么您只需检查您要返回的数据,查看它是否具有指示其为错误响应的相关数组键,并相应地处理它。它返回JSON,不管,如果您使用的是基于承诺的
$.ajax
接口,那么您可以使用
promise.catch()
-像
$.ajax({…}).catch(函数(){/*无论您想对错误做什么*/}),来定义错误处理程序
function LoadDataFromApi(apiUrl) {
    if (!requestCache[apiUrl]) {
        var result = $.ajax({
            type: 'GET',
            url: apiUrl,
            dataType: "json",
            statusCode: {
                // JQuery now has an jqXHR containing all the data we need regarding any success/failures (as we can address multiple status codes here)
                500: function (xhr) {
                    // Parse the JSON data we expected
                    var err = JSON.parse(xhr.responseText);
                    // Display the error data
                    console.log('Message:' + err.Message);
                    console.log('ExceptionMessage:' + err.ExceptionMessage);
                    console.log('ExceptionType:' + err.ExceptionType);
                },
                200: function (xhr) {
                    // console.log('success');
                    // var goodData = JSON.parse(xhr.responseText);
                }
            }
        });
        // This line would generally go in success, but I need to re-use the data regardless of the status code
        requestCache[apiUrl] = result;
    }
    return requestCache[apiUrl];
}