【问题标题】:How to handle rendering exception in mvc?如何处理mvc中的渲染异常?
【发布时间】:2011-04-10 22:17:23
【问题描述】:

如何在 mvc 中捕获渲染异常? (我使用的是第一个版本)

我从值得的案例场景开始 - .ascx 文件中的编译时错误,这是我发现的:

1) 在调试模式下,Visual Studio 说 Controller.ExecuteCore(), InvokeAction 行中存在未处理的异常:

try {
      string actionName = RouteData.GetRequiredString("action");
      if (!ActionInvoker.InvokeAction(ControllerContext, actionName)) { // this line
          HandleUnknownAction(actionName);
     }
}
finally {
   TempData.Save(ControllerContext, TempDataProvider);
}

2) Application.OnError 没有被调用

3) Controller.OnError 没有被调用

4) 当我在这里注入 catch() 时,它也没有被触发。

5) try.. 在 masterpage 中的 catch 没有被触发(尽管它存在于 stacktrace 中!)

6) try.. 页面中的捕获未触发(它也存在于堆栈跟踪中!)

当我包装特定的 RenderPartial 方法时,我能够捕获异常,如下所示:

<% try
   { %>
    <%Html.RenderPartial("Search/" + Model.SearchCategory + "SearchList", Model); %>
    <%}
   catch (Exception ex)
   { %><% HttpContext.Current.Response.Redirect("/en/App/Error"); %><% } %>

我还能做什么?

  • 我无法返回 RedirectAction 因为我们不在控制器中
  • 我试试 HttpContext.Current.Response.Redirect 但它并没有真正起作用(我是 有文本的页面:对象已移动 到 .)

【问题讨论】:

    标签: asp.net-mvc error-handling


    【解决方案1】:

    不确定这是否会有所帮助,但您是否尝试过在项目中打开 MvcBuildViews 选项?据我了解(我自己仍在学习 MVC),视图是“按需”编译的,而不是在项目构建时编译的。这可能会显示以前未检测到的错误。该设置默认关闭。

    要打开它,请在 VS 中卸载项目,打开项目文件并将 XML 中的 MvcBuildViews 选项更改为“true”。然后重新加载项目。

    【讨论】:

    • 这个问题也有关于 MvcBuildViews 选项的详细信息:link
    • 感谢您的评论。我刚刚验证过,行为也与其他异常相同,例如 NUllReferenceException
    【解决方案2】:

    看看使用过滤器属性来捕捉这种行为。

    例如:

    public class CustomAttribute : ActionFilterAttribute
    {
          public override void OnResultExecuted(ResultExecutedContext filterContext)
          {
               if(filterContext.Exception != null)
               {
                    //YOU SHOULD BE ABLE TO SEE YOUR EXCEPTION HERE. 
                    Trace.WriteLine(Exception.Message);
               }
           }
    }
    

    然后用[CustomAttribute]装饰你的控制器类

    [CustomAttribute]
    public class SomeController : Controller
    {
     //Controller stuff
    }
    

    您还有其他一些可用的覆盖,所以请看一下。

    【讨论】:

      猜你喜欢
      • 2012-06-30
      • 2013-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多