2014-03-05 102 views
3

有沒有任何方法覆蓋Elmah記錄的錯誤消息而不復制它?覆蓋Elmah記錄的錯誤消息

我有一個自定義異常類:

public class BusinessException : Exception 
{ 
    // detailed error message used for logging/debugging 
    public string InternalErrorMessage { get; set; } 

    public BusinessException(string message, string internalMessage) 
     :base(message) 
    { 
     InternalErrorMessage = internalMessage; 
    } 
} 

從代碼,我拋出一個異常這樣的:

string detailedErrorMessage = string.Format("User {0} does not have permissions to access CreateProduct resource", User.Identity.Name); 
throw new BusinessException("Permission denied", detailedErrorMessage); 

當ELMAH記錄錯誤,它只是記錄Permission denied消息。但是,我需要記錄異常的InternalErrorMessage屬性。

我試圖創建一個自定義HandleErrorAttribute要做到這一點,但這種複製的例外記錄:

public class ErrorHandleAttribute : HandleErrorAttribute 
{ 
    public override void OnException(ExceptionContext filterContext) 
    { 
     if (filterContext.ExceptionHandled == true) 
      return; 

     Exception exception = filterContext.Exception; 

     BusinessException businessException = exception as BusinessException; 
     if (businessException != null) 
     { 
      ErrorSignal.FromCurrentContext().Raise(new Exception(businessException.InternalErrorMessage, exception)); 
     } 
    } 
} 

enter image description here

回答

0

我懷疑你需要創建自己的錯誤日誌實現來記錄標準屬性以外的任何東西。這不應該太難。

使用SqlErrorLog作爲一個例子,你只需要重寫log方法&把自己的邏輯來修改一下Error類調​​用基實現之前包含。

使用@Matthew也曾經說過的話會阻止你記錄異常兩次。

所有的源代碼是here

+0

這不是我希望的解決方案,但我想我沒有別的選擇 – Catalin

2

我覺得你的問題可能是在這裏:

if (businessException != null) { 
     ErrorSignal.FromCurrentContext().Raise(
      new Exception(businessException.InternalErrorMessage, exception)); 
    } 

當你創建一個新的例外,而不是像這樣:

if (businessException != null) { 
     ErrorSignal.FromCurrentContext().Raise(businessException)); 
    } 

我已經完成了我的網站之一的代碼,並可以看到我是否可以在今天晚些時候重新創建您的問題(假設這不起作用)。我想,這就是後,幫助我實現:How to get ELMAH to work with ASP.NET MVC [HandleError] attribute?

編輯:

重讀你的問題,對方的回答我意識到我是想解決您試圖修正,而不是實際的問題。您是否嘗試過類似this solution這是隻有從當前的嘗試稍有偏差:

public override void OnException(ExceptionContext filterContext) { 
    if (filterContext.ExceptionHandled == true) { 
     return; 
    } 
    Exception exception = filterContext.Exception; 

    BusinessException businessException = exception as BusinessException; 
    if (businessException != null) { 
     var customEx = new Exception(
      businessException.InternalErrorMessage, new BusinessException()); 
     ErrorSignal.FromCurrentContext().Raise(customEx); 
     return; 
    } 
} 

檢查InternalErrormessage正在返回你所期望的,而且我希望迫使這裏return將防止登錄兩次例外。否則,它基本上是你所做的。

+0

剛開我的項目,我沒有寫的自定義處理程序。讓我知道這是不是你的問題,我會盡量在週末複製。 – Matthew

+0

重新閱讀您的問題後更新。 – Matthew

+0

返回將是一個好主意,但'ErrorHandleAttribute'也用於設置結果類型(創建一個JSON錯誤對象以返回給用戶) – Catalin