MVC使用Exception过滤器自定义处理Action的的异常
1.继承FilterAttribute ,IExceptionFilter自定义处理
/// <summary> /// 登录错误自定义处理 /// </summary> public class LoginErrorFilter :FilterAttribute ,IExceptionFilter { public string Title { get; set; } public LoginErrorFilter(string Title) { this.Title = Title; } public void OnException(ExceptionContext filterContext) { //获取出错描述 string msg = this.Title + "时,"; Exception ex = filterContext.Exception; msg += ex.Message; if (ex.InnerException != null) { msg += ",内部错误:" + ex.InnerException.Message; } //执行当前错误页面 RouteData routeData = new RouteData(); routeData.Values.Add("controller", "login"); routeData.Values.Add("action", "error"); routeData.Values.Add("msg", msg); IController one = new LoginController(); one.Execute(new RequestContext(new HttpContextWrapper(HttpContext.Current), routeData)); //返回状态500 filterContext.HttpContext.Response.StatusCode = 500; filterContext.ExceptionHandled = true; filterContext.Result = null; } }
2.操作注释,使用处理
/// <summary> /// QQ第三方登录处理 /// </summary> /// <returns></returns> [LoginErrorFilter("QQ登录处理")] public ActionResult QQOperate() { throw new Exception("错误003"); return result; }