问题描述
如何处理控制器引发的异常时,jQuery的AJAX调用一个动作?
How do I handle exceptions thrown in a controller when jquery ajax calls an action?
例如,我想这会激发一个Ajax调用它,如果在调试模式或者只是一个正常的错误消息显示异常消息中的任何类型的服务器异常执行的全局JavaScript code。
For example, I would like a global javascript code that gets executed on any kind of server exception during an ajax call which displays the exception message if in debug mode or just a normal error message.
在客户端,我将呼吁Ajax错误的功能。
On the client side, I will call a function on the ajax error.
在服务器端,我需要写一个自定义actionfilter?
On the server side, Do I need to write a custom actionfilter?
推荐答案
如果服务器发送一些状态code超过200种不同,错误回调执行:
If the server sends some status code different than 200, the error callback is executed:
$.ajax({
url: '/foo',
success: function(result) {
alert('yeap');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert('oops, something bad happened');
}
});
和注册一个全局错误处理程序,你可以使用方式:
and to register a global error handler you could use the $.ajaxSetup()
method:
$.ajaxSetup({
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert('oops, something bad happened');
}
});
另一种方法是使用JSON。所以,你可以写一个捕获异常并将它们转换成JSON响应服务器上的自定义操作过滤器:
Another way is to use JSON. So you could write a custom action filter on the server which catches exception and transforms them into JSON response:
public class MyErrorHandlerAttribute : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
filterContext.ExceptionHandled = true;
filterContext.Result = new JsonResult
{
Data = new { success = false, error = filterContext.Exception.ToString() },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
,然后装饰与此属性的控制器动作:
and then decorate your controller action with this attribute:
[MyErrorHandler]
public ActionResult Foo(string id)
{
if (string.IsNullOrEmpty(id))
{
throw new Exception("oh no");
}
return Json(new { success = true });
}
和最后调用它:
$.getJSON('/home/foo', { id: null }, function (result) {
if (!result.success) {
alert(result.error);
} else {
// handle the success
}
});
这篇关于ASP.NET MVC Ajax的错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!