ASP.NET MVC Ajax错误处理

Sha*_*ean 115 asp.net-mvc jquery asp.net-mvc-3

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

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

在客户端,我将调用ajax错误的函数.

在服务器端,我是否需要编写自定义actionfilter?

Dar*_*rov 161

如果服务器发送的某些状态代码不是200,则执行错误回调:

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

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

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

另一种方法是使用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
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

然后用这个属性装饰你的控制器动作:

[MyErrorHandler]
public ActionResult Foo(string id)
{
    if (string.IsNullOrEmpty(id))
    {
        throw new Exception("oh no");
    }
    return Json(new { success = true });
}
Run Code Online (Sandbox Code Playgroud)

最后调用它:

$.getJSON('/home/foo', { id: null }, function (result) {
    if (!result.success) {
        alert(result.error);
    } else {
        // handle the success
    }
});
Run Code Online (Sandbox Code Playgroud)


Ara*_*ami 72

谷歌搜索后,我写了一个基于MVC动作过滤器的简单异常处理:

public class HandleExceptionAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAjaxRequest() && filterContext.Exception != null)
        {
            filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            filterContext.Result = new JsonResult
            {
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                Data = new
                {
                    filterContext.Exception.Message,
                    filterContext.Exception.StackTrace
                }
            };
            filterContext.ExceptionHandled = true;
        }
        else
        {
            base.OnException(filterContext);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

并写入global.ascx:

 public static void RegisterGlobalFilters(GlobalFilterCollection filters)
 {
      filters.Add(new HandleExceptionAttribute());
 }
Run Code Online (Sandbox Code Playgroud)

然后在布局或母版页面上编写此脚本:

<script type="text/javascript">
      $(document).ajaxError(function (e, jqxhr, settings, exception) {
                       e.stopPropagation();
                       if (jqxhr != null)
                           alert(jqxhr.responseText);
                     });
</script>
Run Code Online (Sandbox Code Playgroud)

最后你应该打开自定义错误.然后享受它:)

  • 精彩的回答!:d (2认同)

ale*_*hro 9

不幸的是,这些答案都不适合我.令人惊讶的是,解决方案更加简单.从控制器返回:

return new HttpStatusCodeResult(HttpStatusCode.BadRequest, e.Response.ReasonPhrase);
Run Code Online (Sandbox Code Playgroud)

并根据需要在客户端上将其作为标准HTTP错误处理.