2012-04-13 70 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