gpt4 book ai didi

asp.net-mvc - ASP.NET MVC Ajax 错误处理

转载 作者:IT王子 更新时间:2023-10-29 03:24:44 25 4
gpt4 key购买 nike

当 jquery ajax 调用 Action 时,如何处理 Controller 中抛出的异常?

例如,我想要一个全局 javascript 代码,它在 ajax 调用期间在任何类型的服务器异常上执行,如果处于 Debug模式则显示异常消息或只是一条普通错误消息。

在客户端,我会在 ajax 错误时调用一个函数。

在服务器端,我需要写一个自定义的actionfilter吗?

最佳答案

如果服务器发送一些不同于 200 的状态码,则执行错误回调:

$.ajax({
url: '/foo',
success: function(result) {
alert('yeap');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert('oops, something bad happened');
}
});

要注册一个全局错误处理程序,您可以使用 $.ajaxSetup()方法:

$.ajaxSetup({
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert('oops, something bad happened');
}
});

另一种方法是使用 JSON。所以你可以在服务器上编写一个自定义操作过滤器来捕获异常并将它们转换为 JSON 响应:

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
};
}
}

然后用这个属性装饰你的 Controller Action :

[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 - ASP.NET MVC Ajax 错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4707755/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com