如何捕捉异常的MVC的看法? [英] how to catch exception of MVC view?

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

问题描述

在控制器,使用try ... catch可以捕获异常。如何捕捉异常的看法?例如,一个视图可能有code这样的:

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?

推荐答案

这个逻辑应该您的控制器内进行处理,而不是查看。例如,如果你正试图与不存在,则重定向到一个错误页面MYID查看产品。

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.

如果一个错误发生,你也可以重定向到一个InvalidProduct认为,将提供更详细的错误描述/指令。

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

编辑:除了人民的意见如下赶上未处理的异常增加[的HandleError]属性或者在您的ActionResult方法声明或控制器(适用于所有ActionResults)

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

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

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