[英]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
};
}
而我的Web 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)
然后,我找到了此链接: 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函数中进行处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.