views:

96

answers:

2

I need to add localization to the exceptions thrown by my application as a lot are ApplicationExceptions and handled and logged to an error report. Ideally I want to create a new Exception, imheriting from ApplicationException that I can pass the resource key as well as arguments to, so that the exception messsage can be built up from the resource information. Unfortunately (I think) the only way to set the message in an exception is in the New()...

I would like something like:

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

However I can only have MyBase.New() as the first line Message is ReadOnly

Does anyone have any recommendations as to how to get localised strings into the Exception handler? I will need this in a few different exceptions, though could go the way of a exceptioncreation function that gets the localised string and creates teh exception, though the stack info would then be wrong. I also don't want too much in the main body before teh Throw as it obviously starts to impinge on readability of the flow.

+2  A: 

Here is a sample of what I do. EmillException inherits from 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); }
     }
    }
}
labilbe
A: 

have a look at this:

http://visualstudiomagazine.com/features/article.aspx?editorialsid=2562

I don't have to deal with localization but it makes allot of sense.

Hath