如何在 getJSON 中捕获服务器错误
How to trap server error in getJSON
我想在我的 getJSON 调用中设置错误处理。
这是我的调用代码:
try
{
$.getJSON(uri)
.done(function (data) {
//do some thing with the result
}).error(errorHandler());
}
catch (err)
{
alert(err);
}
function errorHandler(page) {
return function (jqXHR, textStatus, errorThrown) {
console.log(page); // it works
};
}
我的网站 api 代码是:
[HttpGet]
public IEnumerable<InformedCommon.Time> GetTimes(string licenseKey, string camIndex, string date, string id, string guid)
{
throw new Exception("hi");
}
未调用错误处理程序代码。
在视图元素控制台我得到:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
然后我发现了这个 link:
http://www.paulbill.com/97/how-to-handle-errors-using-getjson-jquery
所以,我重新编码如下:
$.ajax({
url: uri,
dataType: 'json',
success: function (data) {
console.log('SUCCESS: ', data);
},
error: function (data) {
console.log('ERROR: ', data);
}
});
但是还是没有捕获到这个错误。
所以:
处理服务器调用错误的最佳方法是什么?
要捕获来自 getJSON 的错误,请使用 .fail,而不是 error
$.getJSON(uri)
.done(function (data) {
//do some thing with the result
}).fail(function(){
//handle your Error here
});
但是如果您在服务器脚本上抛出异常,它不会传输到客户端 - 只是 500 内部服务器错误。
我认为您应该在服务器端捕获异常并将其发送到 JSON 到客户端,然后在 .done 函数中处理它。
我想在我的 getJSON 调用中设置错误处理。
这是我的调用代码:
try
{
$.getJSON(uri)
.done(function (data) {
//do some thing with the result
}).error(errorHandler());
}
catch (err)
{
alert(err);
}
function errorHandler(page) {
return function (jqXHR, textStatus, errorThrown) {
console.log(page); // it works
};
}
我的网站 api 代码是:
[HttpGet]
public IEnumerable<InformedCommon.Time> GetTimes(string licenseKey, string camIndex, string date, string id, string guid)
{
throw new Exception("hi");
}
未调用错误处理程序代码。
在视图元素控制台我得到:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
然后我发现了这个 link: http://www.paulbill.com/97/how-to-handle-errors-using-getjson-jquery
所以,我重新编码如下:
$.ajax({
url: uri,
dataType: 'json',
success: function (data) {
console.log('SUCCESS: ', data);
},
error: function (data) {
console.log('ERROR: ', data);
}
});
但是还是没有捕获到这个错误。
所以: 处理服务器调用错误的最佳方法是什么?
要捕获来自 getJSON 的错误,请使用 .fail,而不是 error
$.getJSON(uri)
.done(function (data) {
//do some thing with the result
}).fail(function(){
//handle your Error here
});
但是如果您在服务器脚本上抛出异常,它不会传输到客户端 - 只是 500 内部服务器错误。
我认为您应该在服务器端捕获异常并将其发送到 JSON 到客户端,然后在 .done 函数中处理它。