如何捕获MVC视图异常? [英] how to catch exception of MVC view?

查看:169
本文介绍了如何捕获MVC视图异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在控制器中,try ... catch可以捕获异常。如何查看异常?例如,视图可能具有如下代码:

In controller, try...catch can catch exception. How to catch exception in view? for example, a view may have code like:

<%= Html.Encode(Model.MyID)%>

如果Model为null,访问视图时会收到异常。在哪里可以捕获异常并将用户重定向到具有用户友好的错误消息的错误页面?

If Model is null, you will get exception when access the view. where to catch the exception and redirect user to a error page with user-friendly error message?

推荐答案

只需将[HandleError]属性添加到Controller类的顶部。这样,您的控制器生成的任何异常都将被处理,用户将被显示/Views/Shared/Error.aspx。传递给该视图的模型是一个System.Web.Mvc.HandleErrorInfo对象。

Simply add the [HandleError] attribute to the top of your Controller class. This way, any exception generated by your Controller will be handled and the user will be presented /Views/Shared/Error.aspx. The model passed to that view is a System.Web.Mvc.HandleErrorInfo object.

控制器:

[HandleError]
public class MyController : Controller
{
  public ActionResult Default()
  {
    MyClass thing = MyClassFactory.Create();
    return View(thing);
  }
}

这是一个最后手段异常处理。大卫的答案最适合您可以提前想到的情况。

This is a for "last resort" exception handling. David's answer is best for those cases you can think of ahead of time.

这篇关于如何捕获MVC视图异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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