MVC使用HandleErrorAttribute处理异常

 

使用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

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值