2012-04-13 69 views
0

我创建了一个属性,以便每当我的网站发生异常时,我都会收到一封详细说明该异常的电子邮件。我有这么远,但我的属性代码似乎不火,如果发生异常:创建属性以检查异常

public class ReportingAttribute : FilterAttribute, IExceptionFilter 
{ 
    public void OnException(ExceptionContext filterContext) 
    { 
     // This will generate an email to me 
     ErrorReporting.GenerateEmail(filterContext.Exception); 
    } 
} 

然后我上面的控制器我做:

[ReportingAttribute] 
public class AccountController : Controller 

的另一种方式做到这一点我的catch块里面有ErrorReporting.GenerateEmail(ex)吗?必须有一个更简单的方法?这就是为什么我认为创建属性来处理这个

+0

派生控制器不'IExceptionFilter.OnException()'只调用上未处理的异常? – 2012-04-13 11:30:50

回答

2

记录所有未捕获的异常的目的,你可以在你Global.asax.cs文件中定义了以下方法:只需通过自身

private void Application_Error(object sender, EventArgs e) 
{ 
    try 
    { 
     // 
     // Try to be as "defensive" as possible, to ensure gathering of max. amount of info. 
     // 

     HttpApplication app = (HttpApplication) sender; 

     if(null != app.Context) 
     { 
      HttpContext context = app.Context; 

      if(null != context.AllErrors) 
      { 
       foreach(Exception ex in context.AllErrors) 
       { 
        // Log the **ex** or send it via mail. 
       } 
      } 

      context.ClearError(); 
      context.Server.Transfer("~/YourErrorPage"); 
     } 
    } 
    catch 
    { 
     HttpContext.Current.Response.StatusCode = (int) HttpStatusCode.InternalServerError; 
     HttpContext.Current.ApplicationInstance.CompleteRequest(); 
    } 
} 
+0

嗯,我想邮寄所有的异常,不管我是否抓到它们 – CallumVass 2012-04-13 11:21:11

+0

如果你发现异常而不重新抛出异常,这是否意味着应用程序可以正常进行?如果可以,为什么你需要邮寄异常?在极少数情况下,当你需要它的时候,你可以在'catch'块中手动编写一行代码。所有未捕获(或重新排列)的异常将自动邮寄给您。 – 2012-04-13 11:27:11

+0

那么我会给你一个例子:我的应用很大程度上依赖于我的web服务,如果由于某种原因导致这种情况发生,我需要将用户登出并告诉他们发生了错误。这工作正常,但作为一个额外的功能,我想收到一封电子邮件,说有问题,所以我可以尝试尽早解决它,现在我有一个围绕我的方法的try/catch来捕获此异常,而不是手动把这段代码写入每个catch块,我认为只需要创建一个属性或者更好的东西就更好了 – CallumVass 2012-04-13 11:31:44

1

Attribute不能定义一个行为,但是它用于在代码数据上做一些标记。你应该写代码,在那里你

  • 得到一个异常
  • 支票在引发异常
  • 如果它存在的方法给定的属性存在,收集并发送你需要的数据。
0

为什么不创建一个基本控制器:

public ApplicationBaseController : Controller 
{ 
    public override void OnException(ExceptionContext context) 
    { 
     //Send your e-mail 
    } 
} 

而且从ApplicationBaseController

public HomeController : ApplicationBaseController 
{ 
    //..... 
} 
+0

我试过这个,但是在发生异常时我没有收到任何邮件 – CallumVass 2012-04-13 11:32:03

+0

您确定您的电子邮件设置配置正确吗?请注意,此方法仅在**未处理的异常**上被调用 – 2012-04-13 11:38:43