我有以下代码调用 API,并缓存结果(以便多次使用):
var requestCache = {};
function LoadDataFromApi(apiUrl) {
if (!requestCache[apiUrl]) {
requestCache[apiUrl] = $.ajax({
type: 'GET',
url: apiUrl,
dataType: "json"
});
}
return requestCache[apiUrl];
}
有时,API 会抛出异常,我会 try catch 并显示该异常。根据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];
}
如果有人能发现我的代码中的问题,我将不胜感激?
最佳答案
我们可以过去一下吗
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>
关于jquery - 捕获 $.ajax 响应中的错误,并显示异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52762394/