使用HandleErrorAttribte类处理异常及步骤
1、可以通过下列两种方式选择一种处理异常
(1)、在类或者方法上直接使用HandleError属性来定义
// 在这里声明
[HandleError]
public class HomeController : Controller
...{
// 或者在这里声明
// [HandleError]
public ActionResult Index()
...{
return View();
}
}
(2)、使用MVC3的Global Filters功能来注册,默认新建MVC项目在Global.asax文件里就已经有了
2、开启web.config根目录里的customErrors(不是views目录下的那个web.config)
代码如下:
<customerrors mode="On" defaultredirect="~/Error/HttpError"> <error redirect="~/Error/NotFound" statuscode="404" /></customerrors>
defaultredirect是设置为所有错误页面转向的错误页面地址,而里面的error元素可以单独定义不同的错误页面转向地址,上面的error行就是定义404所对应的页面地址。
3、定义我们所需要的错误页面的ErrorController:
public class ErrorController : BaseController
{
//
// GET: /Error/
public ActionResult HttpError()
{
return View("Error");
}
public ActionResult NotFound()
{
return View();
}
public ActionResult Index()
{
return RedirectToAction("Index", "Home");
}
}
默认Error的view是/views/shared/Error.cshtml文件,我们来改写一下这个view的代码,代码如下:
@model System.Web.Mvc.HandleErrorInfo
@{
ViewBag.Title = "General Site Error";
}
<h2>A General Error Has Occurred</h2>
@if (Model != null)
{
<p>@Model.Exception.GetType().Name<br />
thrown in @Model.ControllerName @Model.ActionName</p>
<p>Error Details:</p>
<p>@Model.Exception.Message</p>
}
文章转载自: MVC使用HandleErrorAttribute自定义异常 http://www.studyofnet.com/news/316.html