Asp.Net MVC3(三)-MvcApp實現全局異常捕獲

定義異常捕獲類:日誌

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
    public class ExceptionAttribute : FilterAttribute, IExceptionFilter
    {
        public virtual void OnException(ExceptionContext filterContext)
        {
            string message = string.Format("消息類型:{0}<br>消息內容:{1}<br>引起異常的方法:{2}<br>引起異常源:{3}"
                , filterContext.Exception.GetType().Name
                , filterContext.Exception.Message
                 , filterContext.Exception.TargetSite
                 , filterContext.Exception.Source + filterContext.Exception.StackTrace
                 );
            
            //記錄日誌
            WriteLog.WriteInfo(message);

            //拋出異常信息
            filterContext.Controller.TempData["ExceptionAttributeMessages"] = message;

            //轉向
            filterContext.ExceptionHandled = true;
            filterContext.Result = new RedirectResult(Globals.ApplicationDirectory + "/Error/ErrorDetail/");
        }
    }

  

Mvc全局使用異常捕獲類:orm

Global.asax.cs文件註冊全局異常捕獲類blog

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
  filters.Add(new Models.ExceptionAttribute());ip


  filters.Add(new HandleErrorAttribute());
}get

實現其餘全局過濾的思想同上.string

相關文章
相關標籤/搜索