ASP.NET MVC 異常處理

iDotNetSpace發表於2009-07-07

在ASP.NET MVC中,進行異常處理變的更為簡單。

方法一:重寫OnException
在需要進行異常處理的Controller中重寫OnException。如果整個程式都需要異常處理,可以先寫一個BaseController,其他所有Controller都繼承它,然後在BaseController中重寫OnException。

 1protected override void OnException(ExceptionContext filterContext)
 2ASP.NET MVC 異常處理{
 3    // 此處進行異常記錄,可以記錄到資料庫或文字,也可以使用其他日誌記錄元件。
 4    // 通過filterContext.Exception來獲取這個異常。
 5    string filePath = @"D:\Temp\Exceptions.txt";
 6    StreamWriter sw = System.IO.File.AppendText(filePath);
 7    sw.Write(filterContext.Exception.Message);
 8    sw.Close(); 
 9
10    // 執行基類中的OnException
11        base.OnException(filterContext);
12
13    // 重定向到異常顯示頁或執行其他異常處理方法
14    Response.Redirect("/");
15}

 

方法二:新增ActionFilter
如果只是想針對某個Action使用異常處理那就不能重寫Controller的OnException了的。但是我們可以先寫一個ExceptionLogAttribute。

 1namespace Snowdream.Demo.MvcExceptionLogging
 2ASP.NET MVC 異常處理{
 3    public class ExceptionLogAttribute:HandleErrorAttribute
 4ASP.NET MVC 異常處理    {
 5        public override void OnException(ExceptionContext filterContext)
 6ASP.NET MVC 異常處理        {
 7            string filePath = @"D:\Temp\Exceptions.txt";
 8            StreamWriter sw = System.IO.File.AppendText(filePath);
 9
10
11            sw.Write(filterContext.Exception.Message);
12            sw.Close();
13
14            base.OnException(filterContext);
15
16            filterContext.HttpContext.Response.Redirect("/");
17        }

18    }

19}

20

然後在需要進行異常處理的Action前加上[ExceptionLog],如:

1[ExceptionLog]
2public ActionResult Index()
3ASP.NET MVC 異常處理{
4    ViewData["Message"= "Welcome to ASP.NET MVC!";
5
6    return View();
7}

8

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/12639172/viewspace-608499/,如需轉載,請註明出處,否則將追究法律責任。

相關文章