學一學MVC的過濾器--異常處理

來源:互聯網
上載者:User

標籤:日誌記錄   過濾器   mvc   


   學習MVC不久,看到公司的項目裡有日誌記錄功能,出於自己的原因一直沒有看看是如何?的,後來看了個學習視頻和一些博文,才發現採用MVC裡的過濾器 Filter 可以很容易實現,比較常見也很容易的做法就是繼承  IActionFilter,IExceptionFilter 介面,然後實現裡面的方法即可。

   下面看一下代碼,這是公司項目的一段代碼,主要是將項目中出現的異常記錄在 每天的txt記錄檔裡。當然實現日誌的方法有很多種,這個只是其中一種,如果出現了IO錯誤,這種方法就不好說啦。

 public class AppHandleErrorAttribute : FilterAttribute, IExceptionFilter    {        public void OnException(ExceptionContext filterContext)        {            //System.Web.Mvc.ExceptionContext            if (!filterContext.ExceptionHandled )            {                //如果已經自己寫了try  catch,那麼可不用記錄日誌                var ds = (System.Web.Configuration.CompilationSection)System.Configuration.ConfigurationManager.GetSection("system.web/compilation");                if (ds.Debug)                {                   //建立相關檔案,並寫入異常記錄                    var dir = System.Web.HttpContext.Current.Server.MapPath("~") + @"\log\";                    if (!System.IO.Directory.Exists(dir)) { System.IO.Directory.CreateDirectory(dir); }                    var path = dir + DateTime.Now.ToString("yyyyMMdd") + "_site.txt";                    using (System.IO.StreamWriter sw = new System.IO.StreamWriter(path, true))                    {                        var dataException = filterContext.Exception;                        var message = dataException.Message;                        sw.WriteLine();                        sw.WriteLine("-----------------"+DateTime.Now.ToString("HH:mm:ss") + "-----------------");                        sw.WriteLine(message);                        sw.WriteLine("Message:" + dataException.Message);                        sw.WriteLine("StackTrace:" + dataException.StackTrace.ToString());                        sw.Flush();                        sw.Close();                    }                }                filterContext.ExceptionHandled = true;//異常已經處理,程式可以不用在處理一遍                //var link = new UrlHelper(filterContext.RequestContext).Action("Index", "CustomError");                //filterContext.Result = new RedirectResult(link);                //filterContext.Result = new ContentResult() { Content = "<center>網路連接異常,請<a href=‘javascript:;‘ onclick=‘location.reload()‘>重新整理</a>重試</cener>", ContentType = "text/html" };                filterContext.Result = new ContentResult() { Content = "<center>當前網路發生故障,請重新整理頁面重試(點擊<a href=‘javascript:;‘ onclick=‘location.reload()‘>重新整理</a>)</cener>", ContentType = "text/html" };            }        }    }

 上邊這段代碼很簡單,如果只是單純記錄某一個Action的Exception,那麼調用方法如下

[AppHandleError]public ActionResult  xxAction(){    return View();}

 如果是全域的設定,那麼就要在項目的Global.ascx 裡面加上這麼一段話,註冊 自訂的Filter

        public static void RegisterGlobalFilters(GlobalFilterCollection filters)        {                      filters.Add(new AppHandleErrorAttribute());        }                protected void Application_Start()        {           //  AreaRegistration.RegisterAllAreas();           //  調用註冊方法               RegisterGlobalFilters(GlobalFilters.Filters);           //  RegisterRoutes(RouteTable.Routes);        }

下面進入實戰Demo


1.編寫AppHandleErrorAttribute,代碼已經貼出

2.在需要記錄異常的Action上添加這個屬性

        [AppHandleError]        public ActionResult Index()        {            throw new Exception("記錄日誌的內容");            return View();        }

先看一下沒加 這個過濾器的頁面,很明顯黃頁:

650) this.width=650;" src="http://s3.51cto.com/wyfs02/M01/35/BD/wKioL1OrjBbAY9m4AAGe497Ec9I191.jpg" title="QQ圖片20140626105238.jpg" alt="wKioL1OrjBbAY9m4AAGe497Ec9I191.jpg" />

下面是添加過濾器的運行效果:650) this.width=650;" src="http://s3.51cto.com/wyfs02/M00/35/C8/wKioL1OrjHyS1vVRAABnFY5bxlg216.jpg" title="QQ圖片20140626105430.jpg" alt="wKioL1OrjHyS1vVRAABnFY5bxlg216.jpg" />

那麼這個頁面就是錯誤處理頁了,我這裡是輸出的內容,也可以將filterContext.Result 設定成為ViewResult,或者跳轉到新的錯誤頁面。再看一下日誌記錄:650) this.width=650;" src="http://s3.51cto.com/wyfs02/M01/35/D3/wKiom1OrjQrBTQTgAAERls29GHA943.jpg" title="QQ圖片20140626104954.jpg" alt="wKiom1OrjQrBTQTgAAERls29GHA943.jpg" />

可以看到,異常日誌已經添加到相關的txt記錄檔裡面。


說明:如果在Global裡面增加了項目配置,那麼在Action上就不用標註這個過濾器,所有未經過Try  catch的異常都可以捕獲處理,代碼,圖略。


所以,try  catch不是什麼情況下都適用,如果不影響重要業務的情況下,可以使用try  catch來處理業務,如果是比較重大的錯誤,就需要日誌記錄了。今天就到這裡吧,第一次寫這種博文,也算是自己的學習感想。有不足或者更好的方法歡迎批評指出。

本文出自 “小盤子的IT空間” 部落格,請務必保留此出處http://panzi.blog.51cto.com/4738203/1431065

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.