how to catch exception of MVC view?

江枫思渺然 提交于 2019-12-20 19:57:49

问题


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)%>

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?


回答1:


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.

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.




回答2:


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

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



回答3:


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




回答4:


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.

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

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

[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);
    }



回答5:


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.

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)




回答6:


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.




回答7:


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.

There's a variety of ways to catch errors here: 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.



来源:https://stackoverflow.com/questions/1074540/how-to-catch-exception-of-mvc-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!