.net 如何捕获MVC视图的异常?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1074540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 12:56:56  来源:igfitidea点击:

how to catch exception of MVC view?

.netasp.net-mvcexception-handling

提问by KentZhou

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

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

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

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?

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

回答by Peter J

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] 属性添加到 Controller 类的顶部。这样,您的控制器生成的任何异常都将被处理,并且用户将看到 /Views/Shared/Error.aspx。传递给该视图的模型是 System.Web.Mvc.HandleErrorInfo 对象。

The controller:

控制器:

[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.

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

回答by The Matt

Consider using Elmah: http://code.google.com/p/elmah/

考虑使用 Elmah:http: //code.google.com/p/elmah/

回答by Paul Schaeflein

You can use try/catch in a script block in the view:

您可以在视图的脚本块中使用 try/catch:

@try
{    
  <div>typical Razor view stuff here...</div>
}
catch (Exception ex)
{
  @<script type="text/javascript">
    alert('@ex.Message.Replace("'","\'").Replace("\r\n","<br/>")');
  </script>
}

回答by Andrei R?nea

Although I support David Liddle's answer ("This logic should be handled inside your Controller and not the View") I can also tell you that you should code defensively in general.

虽然我支持 David Liddle 的回答(“这个逻辑应该在你的控制器而不是视图中处理”),但我也可以告诉你,你应该在一般情况下进行防御性编码。

For example instead of

例如代替

try
{
    Html.Encode(Model.MyID)
}
catch
{
    Response.Redirect("~/Error/500");
}

you should

你应该

if (Model == null)
{
    // ...
}
else
{
    //.....
}

(ofcourse, again, don't put view selection logic in a view)

(当然,同样,不要将视图选择逻辑放在视图中)

回答by David

This logic should be handled inside your Controller and not the View. For example if you are trying to view a Product with MyID that does not exist then redirect to an error page.

这个逻辑应该在你的控制器而不是视图中处理。例如,如果您尝试查看 MyID 不存在的产品,则重定向到错误页面。

If an error has occured you could also redirect to an InvalidProduct view that would provide a more detailed error description/instructions.

如果发生错误,您还可以重定向到 InvalidProduct 视图,该视图将提供更详细的错误描述/说明。

Edit: In addition to peoples comments below to catch unhandled exceptions add the [HandleError] attribute either on your ActionResult method declaration or on the Controller (for all ActionResults).

编辑:除了下面的人们评论以捕获未处理的异常之外,在您的 ActionResult 方法声明或控制器(对于所有 ActionResults)上添加 [HandleError] 属性。

[HandleError]
public ProductsController
{
    public ActionResult Show(int id)
    {
        Product p = //e.g. get product from db

        if (p == null)
        {
            return RedirectToAction("Error");
            //return RedirectToAction("InvalidProduct");
        }

        return View(p);
    }

回答by Matthew Groves

Well, you can't always catch every error in the controller, but hopefully your views should be lightweight enough where it's very unlikely to happen.

好吧,你不能总是捕获控制器中的每个错误,但希望你的视图应该足够轻量级,它不太可能发生。

However, if an exception does get thrown in the view, you should have a custom 500 error page set up to redirect the user to just in case. I believe you can set up a redirect like this in the Global.asax or it might be an IIS setting as well.

但是,如果视图中确实抛出了异常,您应该设置一个自定义的 500 错误页面以将用户重定向到以防万一。我相信您可以在 Global.asax 中设置这样的重定向,或者它也可能是 IIS 设置。

回答by John Tseng

I agree with Matthew Groves that you can't always catch every error. Unfortunately in my case, I have a view that has 100 something variables. It's hard to account for all of them.

我同意 Matthew Groves 的观点,你不能总是抓住每一个错误。不幸的是,在我的情况下,我有一个包含 100 个变量的视图。很难解释所有这些。

There's a variety of ways to catch errors here: http://www.codeproject.com/Articles/850062/Exception-handling-in-ASP-NET-MVC-methods-explaine

这里有多种捕获错误的方法:http: //www.codeproject.com/Articles/850062/Exception-handling-in-ASP-NET-MVC-methods-explaine

In my case, I wanted to record the error that has occurred in the view with the data that was used in the controller. So I chose to override OnException in my controller. This way, during the action, I can store my data on the controller instance and then access it later in the OnException method.

就我而言,我想用控制器中使用的数据记录视图中发生的错误。所以我选择在我的控制器中覆盖 OnException。这样,在操作期间,我可以将我的数据存储在控制器实例上,然后稍后在 OnException 方法中访问它。

回答by live-love

Try this code if you want to redirect to an error action inside the cshtml:

如果您想重定向到 cshtml 中的错误操作,请尝试以下代码:

                @{
                    try
                    {
                        Html.Action("GetCurrentUser", "Layout");
                    }
                    catch (Exception)
                    {
                        Response.Redirect("~/Error");
                    }
                }