【问题标题】:How to write a LogExceptionAttribute for MVC3 Site?如何为 MVC3 站点编写 LogExceptionAttribute?
【发布时间】:2012-11-06 04:23:11
【问题描述】:
在每个动作中,我都会写:
public ActionResult Foo()
{
try
{
// Do something
}
catch(Exception ex)
{
Logger.Error("Foo()", ex);
}
...
}
我知道 MVC3 有能力在 Global.asax 中“注册全局过滤器”,所以我想写一个自定义的 LogExceptionAttribute。这将:
-
which Action导致what Exception的日志信息。调用我的 Logger API:
Logger.Error(string actionName, Exception ex)
再次抛出异常。这样 web.config 中的 CustomError 就会显示用户错误页面。
如何实现?
【问题讨论】:
标签:
asp.net-mvc-3
logging
exception-handling
attributes
【解决方案1】:
试试这个
public class HandleErrorHmAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext context)
{
base.OnException(context);
new WebRequestErrorEventMvc("An unhandled exception has occurred.", this, 103005, context.Exception).Raise();
}
}
public class WebRequestErrorEventMvc : WebRequestErrorEvent
{
public WebRequestErrorEventMvc(string message, object eventSource, int eventCode, Exception exception) : base(message, eventSource, eventCode, exception) { }
public WebRequestErrorEventMvc(string message, object eventSource, int eventCode, int eventDetailCode, Exception exception) : base(message, eventSource, eventCode, eventDetailCode, exception) { }
}