2013-04-26 77 views
1

在我的應用程序時出現異常,我需要從業務層 此基礎上,錯誤代碼,我需要證明可在消息傳遞錯誤代碼表示層DB。
我想知道如何傳遞BL中的錯誤代碼並獲取表示層中的錯誤代碼。
對於日誌記錄異常我使用log4net和企業庫4.0。傳遞錯誤代碼從Exception在C#

在此先感謝

+0

http://stackoverflow.com/questions/7135492/asp-net-displaying-business-layer-errors-in-the-presentation-layer – 2013-04-26 07:07:05

+0

http://stackoverflow.com/questions/2210841/什麼是正確的方式傳遞一個例外-c – Freelancer 2013-04-26 07:08:45

+1

我建議你自己寫一個類使用公共靜態方法doLogToMyDatabase(String aError);那麼當你捕獲一個exeption只需調用該方法將寫入你的數據庫,你需要什麼。 – 2013-04-26 07:12:16

回答

1

您可以創建自己的業務異常來自Exception繼承,並且使課堂接受你的錯誤代碼。此類將成爲您的域的一部分,因爲這是一個業務例外。與數據庫例外等基礎設施例外無關..

public class BusinessException : Exception 
{ 
    public int ErrorCode {get; private set;} 

    public BusinessException(int errorCode) 
    { 
    ErrorCode = errorCode; 
    } 
} 

您還可以使用枚舉或常量。我不知道你的ErrorCode類型。

在業務層,你可以通過拋出異常:

throw new BusinessException(10); //If you are using int 
throw new BusinessException(ErrorCodes.Invalid); //If you are using Enums 
throw new BusinessException("ERROR_INVALID"); // 
所以在表示層後

您可以捕獲該異常,並根據您的需要對其進行處理。

public void PresentationMethod() 
{ 
    try 
    { 
     _bll.BusinessMethod(); 
    } 
    catch(BusinessException be) 
    { 
     var errorMessage = GetErrorMessage(be.ErrorCode); 
     ShowErrorUI(errorMessage); 
    } 
}