The title is a bit abstract so maybe it is easier to explain with a specific example:
I find it useful to have my exception classes take an enum parameter instead of a string message.
throw new SpecificException(SpecificExceptionCode.ThisThingWentWrong);
There are few reasons for this, including:
- I can encapulate all the logic for accessing localized string resources in one place
- I can easily make sure I have string resources for all my exception messages
- Checking for correct exception messages in unit tests is simpler
I would like to write a base class for this type of exception. Derived exception classes generally just want to provide their own System.Resources.ResourceManager but may also provide additional constructors. The trouble comes because I can only call static methods in calls to base class constructors. This leads me to something like:
public abstract class BaseException : ApplicationException
{
protected static ResourceManager m_resources;
public BaseException(System.Enum errorCode, params object[] messageArgs)
: base(ProcessError(errorCode, messageArgs))
{}
private static string ProcessError(Enum errorCode, params object[] messageArgs)
{
string errorMessage = m_resources.GetString(errorCode.ToString());
// Handling of messageArgs and trace logging
// ....
return finalError;
}
}
and
public class SpecificException : BaseException
{
static SpecificException()
{
m_resources = //.. Get an appropriate resource manager instance
}
public SpecificException(SpecificExceptionCode errorCode, params object[] messageArgs)
: base(errorCode, messageArgs)
{}
}
This works, but I am unhappy with it as there is no compile time hint that the derived class must provide its own System.ResourceManager
. I would like to have a base class such as:
public abstract class BaseException : ApplicationException
{
protected abstract static ResourceManager Resources{get;}
public BaseException(System.Enum errorCode, params object[] messageArgs)
: base(ProcessError(errorCode, messageArgs))
{}
private static string ProcessError(Enum errorCode, params object[] messageArgs)
{
string errorMessage = Resources.GetString(errorCode.ToString());
// Handling of messageArgs and trace logging
// ....
return finalError;
}
}
...but I cannot have an abstract static method. Is there a better way?