With our public SDK, we tend to want to give very informative messages about why an exception occurs. For example:
if (interfaceInstance == null)
{
string errMsg = string.Format(
"Construction of Action Argument: {0}, via the empty constructor worked, but type: {1} could not be cast to type {2}.",
ParameterInfo.Name,
ParameterInfo.ParameterType,
typeof(IParameter)
);
throw new InvalidOperationException(errMsg);
}
However, this tends to clutter up the flow of the code, as it tends to put a lot of focus on error messages rather than what the code is doing.
A colleague started refactoring some of the exception throwing to something like this:
if (interfaceInstance == null)
throw EmptyConstructor();
...
private Exception EmptyConstructor()
{
string errMsg = string.Format(
"Construction of Action Argument: {0}, via the empty constructor worked, but type: {1} could not be cast to type {2}.",
ParameterInfo.Name,
ParameterInfo.ParameterType,
typeof(IParameter)
);
return new InvalidOperationException(errMsg);
}
Which makes the code logic easier to understand, but adds a lot of extra methods to do error handling.
What are other ways to avoid the "long-exception-messages clutter logic" problem? I'm primarily asking about idiomatic C#/.NET, but how other languages manage it are helpful as well.
[Edit]
It would be nice to have the pros and cons of each approach as well.
Exception.Data
property, "picky" exception catching, calling code catching & adding its own context, along with the captured call stack all contribute information that should allow far less verbose messages. FinallySystem.Reflection.MethodBase
looks promising for providing details to pass to your "exception construction" method. – radarbob Dec 16 '13 at 4:11Exception.Data
. The emphasis should be capturing telemetry. Refactoring here is fine, but it misses the problem. – radarbob Dec 18 '13 at 2:56