愛上(shang)MVC3系列~全局異常(chang)處理與異常(chang)日志
在(zai)MVC3網站的global.asax中的Application_Start方(fang)法里,有這(zhe)樣一段(duan)代碼
1 RegisterGlobalFilters(GlobalFilters.Filters);
它(ta)的主要(yao)使用是(shi)將全局過(guo)濾器進(jin)行注(zhu)冊(ce),而全局過(guo)濾器可以(yi)在RegisterGlobalFilters這個方法里進(jin)行設(she)置,如代碼:
1 /// <summary> 2 /// 全局過濾器(特性) 3 /// </summary> 4 /// <param name="filters"></param> 5 public static void RegisterGlobalFilters(GlobalFilterCollection filters) 6 { 7 // ExceptionLogAttribute繼承(cheng)自(zi)HandleError,主要(yao)作用是將異常信息寫入日志(zhi)系統中 8 filters.Add(new Web.Commons.Attributes.ExceptionLogAttribute()); 9 //默認(ren)的異常記(ji)錄類(lei) 10 filters.Add(new HandleErrorAttribute()); 11 }
當我們設置完上面兩塊后,現在如果想記異常日志,那我們需要完善一下ExceptionLogAttribute這個類,看代碼:
1 /// <summary> 2 /// 異常持久化類 3 /// </summary> 4 public class ExceptionLogAttribute : HandleErrorAttribute 5 { 6 /// <summary> 7 /// 觸(chu)發異常(chang)時調(diao)用(yong)的方法(fa) 8 /// </summary> 9 /// <param name="filterContext"></param> 10 public override void OnException(ExceptionContext filterContext) 11 { 12 13 string message = string.Format("消(xiao)息類型:{0}<br>消(xiao)息內容(rong):{1}<br>引發異常(chang)(chang)(chang)的方法:{2}<br>引發異常(chang)(chang)(chang)的對象:{3}<br>異常(chang)(chang)(chang)目錄:{4}<br>異常(chang)(chang)(chang)文件:{5}" 14 , filterContext.Exception.GetType().Name 15 , filterContext.Exception.Message 16 , filterContext.Exception.TargetSite 17 , filterContext.Exception.Source 18 , filterContext.RouteData.GetRequiredString("controller") 19 , filterContext.RouteData.GetRequiredString("action")); 20 VLog.VLogFactory.CreateVLog().ErrorLog(message); //TODO:將(jiang) ex 錯誤對象記錄到系統日志模塊 21 base.OnException(filterContext); 22 } 23 }
大家可以看到,在上面類(lei)中(zhong)(zhong),有個CreateVLog的(de)方(fang)法,它是(shi)干(gan)什么(me)用的(de)呢,實(shi)事上,它就(jiu)是(shi)我(wo)們的(de)日志功能(neng)類(lei),可以對日志進行不同類(lei)型的(de)持久化,這我(wo)會(hui)在單獨一(yi)講中(zhong)(zhong)去(qu)說明它。
今(jin)天主要就是MVC3中的全(quan)局異常(chang)的記(ji)錄(lu)方法,呵呵。