【问题标题】:Catch error in $.ajax response, and display exception捕获 $.ajax 响应中的错误,并显示异常
【发布时间】:2018-10-11 14:17:05
【问题描述】:

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

var requestCache = {};
function LoadDataFromApi(apiUrl) {
    if (!requestCache[apiUrl]) {
        requestCache[apiUrl] = $.ajax({
            type: 'GET',
            url: apiUrl,
            dataType: "json"
        });
    }
    return requestCache[apiUrl];
}

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

{
   "Message":"An error has occurred.",
   "ExceptionMessage":"Invalid object name 'Foo_Bar'.",
   "ExceptionType":"System.Data.SqlClient.SqlException",
}

JQuery documentation,我看到$.ajax 中有一个statusCode 对象,但我无法成功实现它。 answer here 已关闭,但实际上并未检索异常消息。

从今天的各种搜索来看,我已经到此为止了,但是 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];
}

如果有人能在我的代码中发现问题,我将不胜感激?

【问题讨论】:

  • 当您的 API 返回错误 JSON 时,它会返回什么 HTTP 状态代码? 200好吗?还是 500 服务器错误或其他一些状态代码?如果它返回 HTTP 200 OK 但带有“错误” JSON 有效负载,那么您只需检查您返回的数据并查看它是否具有指示它是错误响应的相关数组键,并处理相应地。
  • 无论如何它都会返回 JSON,但错误返回 500,成功返回 200。
  • 如果您使用$.ajax 的基于promise 的接口,那么您可以使用Promise.catch() 定义您的错误处理程序——例如$.ajax({...}).catch(function() { /* whatever you want to do with the error */ });

标签: jquery json ajax


【解决方案1】:

我们可以过去吗

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>

【讨论】:

    【解决方案2】:

    经过大量搜索,我终于弄明白了,感谢this answer

    问题出在这里:

    500: function (json) {
    

    事实证明,虽然 API 返回 JSON 数据,但 JQuery 将其包装在一个 jqXHR object 中,该 jqXHR object 具有许多属性。

    我期望的 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];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-20
      • 2016-10-29
      • 1970-01-01
      • 2017-04-22
      • 1970-01-01
      • 2015-06-11
      • 2014-03-21
      • 1970-01-01
      相关资源
      最近更新 更多