标签:com ror pre 继承 exception ati start string mvc
创建一个异常处理类ExceptionFilters,继承System.Web.Mvc.FilterAttribute, System.Web.Mvc.IExceptionFilter 实现方法OnException
public class ExceptionFilters : System.Web.Mvc.FilterAttribute, System.Web.Mvc.IExceptionFilter { public void OnException(ExceptionContext filterContext) { if (!filterContext.ExceptionHandled) { string controllerName = (string)filterContext.RouteData.Values["controller"]; string actionName = (string)filterContext.RouteData.Values["action"]; string ip = HttpContext.Current.Request.UserHostAddress; string param = filterContext.HttpContext.Request.HttpMethod; //记录日志 LogFile.WriteErrorLog(DateTime.Now + string.Format(" Location:{0}/{1} Param:{2} UserIP:{3} Exception:{4}", controllerName, actionName, param, ip, filterContext.Exception.Message)); //设置返回结果 filterContext.Result = new JsonResult { Data = new ResultU { IsOK = false, Code = 999, Msg = filterContext.Exception.Message }, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } filterContext.ExceptionHandled = true;//返回结果是JsonResult,则设置异常已处理 } }
在过滤器中注册
在App_Start/FilterConfig.cs
public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { //filters.Add(new HandleErrorAttribute()); filters.Add(new ExceptionFilters()); } }
测试返回 写入日志
标签:com ror pre 继承 exception ati start string mvc
原文地址:https://www.cnblogs.com/shenghuotaiai/p/12300572.html