ASP.NET MVC 3自定义异常过滤器OnException不会触发

时间:2012-10-01 10:29:59

标签: asp.net-mvc json asp.net-mvc-3

我正在开发一个ASP.NET MVC 3项目,我想实现我的自定义错误处理逻辑。我试图通过像这样扩展HandleErrorAttribute:

public class ErrorHandlingAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        if (!filterContext.ExceptionHandled)
        {
            filterContext.Result = new JsonResult { 
                                                    Data = new { success = false, error = filterContext.Exception.ToString() }, 
                                                    JsonRequestBehavior = JsonRequestBehavior.AllowGet 
                                                  };
            filterContext.ExceptionHandled = true;
        }
    }
}

在一些AJAX调用之后,我需要在模态弹出对话框中显示一些错误消息(通过渲染局部视图)。因此,在OnException方法中,我将ExceptionContext的结果设置为JsonResult(我现在不将部分视图呈现为字符串,我稍后会这样做)

我的控制器操作如下(我用自定义过滤器修饰):

 [HttpPost]
 [ErrorHandling]
 public JsonResult Create(StopEditViewModel viewModel)
 {
        Stop stop = Mapper.Map<StopViewModel, Stop>(viewModel.Stop);

        if (ModelState.IsValid)
        {
            Stop addedStop = _testFacade.AddStop(stop);

            return Json(new { success = true, tableContainer = _tableName }, JsonRequestBehavior.DenyGet);
        }

        return Json(new { success = false }, JsonRequestBehavior.DenyGet);
 }

在做了一些研究之后,我发现我需要从Global.asax中的RegisterGlobalFilters方法中删除filters.Add(new HandleErrorAttribute());行。我也这样做了。

我的web.config文件有<customErrors mode="On" />标记。

但是当我调用Create POST操作时,如果发生异常,则不会调用自定义过滤器方法。应用程序崩溃。我错过了什么吗?

感谢。

1 个答案:

答案 0 :(得分:1)

您可以在ajax选项中捕获异常 OnFailure 方法

In View
@using (Ajax.BeginForm("SomeAction", new AjaxOptions { OnFailure = "handleAjaxError" }))
{

}

function handleAjaxError(ajaxContext) {
     alert("Request failed, status code ");
}

当您使用Ajax调用action时,它会在方法内返回。