之前我寫過一篇關於ASP.NET全域異常處理的文章(http://www.cnblogs.com/snowdream/archive/2008/07/03/1234402.html)。在ASP.NET MVC中,進行異常處理變的更為簡單。
方法一:重寫OnException
在需要進行異常處理的Controller中重寫OnException。如果整個程式都需要異常處理,可以先寫一個BaseController,其他所有Controller都繼承它,然後在BaseController中重寫OnException。
1protected override void OnException(ExceptionContext filterContext)
2{
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
2{
3 public class ExceptionLogAttribute:HandleErrorAttribute
4 {
5 public override void OnException(ExceptionContext filterContext)
6 {
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()
3{
4 ViewData["Message"] = "Welcome to ASP.NET MVC!";
5
6 return View();
7}
8
樣本下載
本文適用於 ASP.NET MVC 1.0