MVC 异常处理机制

时间:2021-03-16 10:37:32

方法一 :web.config配置文件的 system.web 接点下添加,若为On则不会将异常信息反馈到用户,而是友好的跳转到error.htm

<customErrors mode="On" defaultRedirect="error.htm">
      <error statusCode="404" redirect="~/error/notfound"></error>
    </customErrors>

方法二:在  FilterConfig.cs 中有 new HandleErrorAttribute() 这样一句话, 此类为微软默认已经有的异常处理类,但是是注释的,方法而的优先级比方法一高。

方法三:自定义异常处理类

此处需要注意的是,和方法二差别不大,就是实现IExceptionFilter借口中的OnException方法,可以认为做一些在异常后的后续处理。

调用可以通过

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {

filters.Add(new CustomExceptionAttribute(), 1);
            filters.Add(new HandleErrorAttribute(), 2);//数字越小优先级越高。
        }

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

namespace Web

{

public class CustomExceptionAttribute : FilterAttribute, IExceptionFilter

{

public void OnException(ExceptionContext filterContext)

{

if (filterContext.ExceptionHandled == true)

{

HttpException httpExce = filterContext.Exception as HttpException;

if (httpExce.GetHttpCode() != 500)//为什么要特别强调500 因为MVC处理HttpException的时候,如果为500 则会自动将其ExceptionHandled设置为true,那么我们就无法捕获异常

{

return;

}

}

HttpException httpException = filterContext.Exception as HttpException;

if (httpException != null)

{

filterContext.Controller.ViewBag.UrlReferrer = filterContext.HttpContext.Request.UrlReferrer;

if (httpException.GetHttpCode() == 404)

{

filterContext.HttpContext.Response.Redirect("~/home/notfound");

}

else if (httpException.GetHttpCode() == 500)

{

filterContext.HttpContext.Response.Redirect("~/home/internalError");

}

}

//写入日志 记录

filterContext.ExceptionHandled = true;//设置异常已经处理

}

}

}