ASP.NET MVC Ajax 错误处理 [英] ASP.NET MVC Ajax Error handling

查看:29
本文介绍了ASP.NET MVC Ajax 错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何处理jquery ajax调用动作时控制器抛出的异常?

How do I handle exceptions thrown in a controller when jquery ajax calls an action?

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

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.

在服务器端,我是否需要编写自定义操作过滤器?

On the server side, Do I need to write a custom actionfilter?

推荐答案

如果服务器发送一些不同于 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');
    }
});

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

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 错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆