1

我正在尝试为我的 mvc 3(razor) 应用程序创建自定义异常。但它不能正常工作。

以下是我为自定义异常类编写的代码。

using System;
using System.Web.Mvc;

namespace TestApp.Helpers
{
    public class CustomExceptionAttribute : FilterAttribute, IExceptionFilter
    {
        public void OnException(ExceptionContext filterContext)
        {
            if (!filterContext.ExceptionHandled && filterContext.Exception is Exception)
            {
                //filterContext.Result = new RedirectResult("/shared/Error.html");
                filterContext.Result = new ViewResult { ViewName = "Error" };
                filterContext.ExceptionHandled = true;
            }
        }
    }
}

以下是控制器中的代码:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
using TestApp.Domain;
using TestApp.Helpers;

namespace TestApp.Controllers
{
    [CustomException]
    public class MyController : Controller
    {
        private TestAppEntities db = new TestAppEntities();

        public ActionResult Create(int id)
        {
           // Throwing exception intentionally
           int a = 1;
           int b = 0;
           int c = a / b;
           //This is another method which is working fine.
           return View(CreateData(id, null));
        }
    }
}

下面是'Error.cshtml'中的代码

@model System.Web.Mvc.HandleErrorInfo
@{
    ViewBag.Title = "Error";
}
<h2>
    Sorry, an error occurred while processing your request.
</h2>
<div>
    <p>
        There was a <b>@Model.Exception.GetType().Name</b> while rendering <b>@Model.ControllerName</b>'s
        <b>@Model.ActionName</b> action.
    </p>
    <p>
        The exception message is: <b><@Model.Exception.Message></b>
    </p>
    <p>Stack trace:</p>
    <pre>@Model.Exception.StackTrace</pre>
</div>

当我们运行应用程序时,它会在@Model.Exception.GetType().Name 处引发错误,因为模型为空。这是确切的错误:NullReferenceException:对象引用未设置为对象的实例。

任何人都可以让我知道错误的确切原因是什么?我怎样才能解决这个问题?

4

1 回答 1

1

您必须将HandleErrorInfo实例传递给视图。

string controllerName = (string)filterContext.RouteData.Values["controller"];
string actionName = (string)filterContext.RouteData.Values["action"];

HandleErrorInfo model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
filterContext.Result = new ViewResult
{
   ViewName = "Error",   
   ViewData = new ViewDataDictionary<HandleErrorInfo>(model)
};
于 2012-11-28T14:37:17.450 回答