2008-11-13 90 views
0

我需要將本地化添加到由我的應用程序拋出的異常中,因爲ApplicationExceptions很多並且處理並記錄到錯誤報告中。理想情況下,我想創建一個新的異常,從ApplicationException繼承,我可以將資源鍵以及參數傳遞給,以便可以從資源信息構建異常消息。不幸的是(我認爲)的一個例外設置郵件的唯一方式是在新的()...關於本地化異常的建議

我想是這樣的:

public class LocalizedException 
    Inherits ApplicationException 

public Sub New(ResourceKey as string, arg0 as Object) 
    MyBase.New() 
    ' get the localized text' 
    Dim ResMan as New Global.System.Resources.ResourceManager("AppName.ExceptionResources", _ 
    System.Reflection.Assembly.GetExecutingAssembly) 
    Dim LocalText as string = ResMan.GetString(ResourceKey) 
    Dim ErrorText as String = "" 
    Try 
     Dim ErrorText = String.Format(LocalText, arg0) 
    Catch 
     ErrorText = LocalText + arg0.ToString() ' in case String.Format fails' 
    End Try 
    ' cannot now set the exception message!' 
End Sub 
End Class 

然而我只能有MyBase.New( )作爲第一行 消息是隻讀

有沒有人有任何關於如何獲得本地化字符串到異常處理程序的建議?我將在幾個不同的例外中需要這個,儘管可能會採用異常創建函數的方式來獲取本地化的字符串並創建異常,儘管堆棧信息將會是錯誤的。在投擲之前,我也不想在主體中太多,因爲它顯然開始影響流的可讀性。

回答

2

下面是我做的一個例子。 EmillException繼承自ApplicationException。


namespace eMill.Model.Exceptions 
{ 
    public sealed class AccountNotFoundException : EmillException 
    { 
     private readonly string _accountName; 

     public AccountNotFoundException(string accountName) 
     { 
      _accountName = accountName; 
     } 

     public override string Message 
     { 
      get { return string.Format(Resource.GetString("ErrAccountNotFoundFmt"), _accountName); } 
     } 
    } 
}