之前我写过一篇关于ASP.NET全局异常处理的文章(http://www.cnblogs.com/snowdream/archive/2008/07/03/1234402.html)。在ASP.NET MVC中,进行异常处理变的更为简单。
方法一:重写OnException
在需要进行异常处理的Controller中重写OnException。如果整个程序都需要异常处理,可以先写一个BaseController,其他所有Controller都继承它,然后在BaseController中重写OnException。
1
protected 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
}
protected 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
// 执行基类中的OnException11
base.OnException(filterContext);12

13
// 重定向到异常显示页或执行其他异常处理方法14
Response.Redirect("/");15
}
方法二:添加ActionFilter
如果只是想针对某个Action使用异常处理那就不能重写Controller的OnException了的。但是我们可以先写一个ExceptionLogAttribute。
1
namespace 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
namespace Snowdream.Demo.MvcExceptionLogging2
{3
public class ExceptionLogAttribute:HandleErrorAttribute4
{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

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

6
return View();7
}8

示例下载
本文适用于 ASP.NET MVC 1.0


浙公网安备 33010602011771号