I was wondering if there was a reasonable way to customize messages on exceptions that are thrown by the .NET framework? Below is a chunk of code that I write often, in many different scenarios to achieve the effect of providing reasonable exception messages to my users.
public string GetMetadata(string metaDataKey)
{
// As you can see, I am doing what the dictionary itself will normally do, but my exception message has some context, and is therefore more descriptive of the actual problem.
if (!_Metadata.ContainsKey(metaDataKey))
{
throw new KeyNotFoundException(string.Format("There is no metadata that contains the key '{0}'!", metaDataKey));
}
// This will throw a 'KeyNotFoundException' in normal cases, which I want, but the message "The key is not present in the dictionary" is not very informative. This is the exception who's message I wish to alter.
string val = _Metadata[metaDataKey].TrimEnd();
return val;
}
As you can see, I am essentially producing duplicate code just to use a different (better) message.
Edit:
What I am looking for, essentially is something like this:
KeyNotFoundException.SetMessage("this is my custom message!")
{
// OK, now this will send off the message I want when the exception appears!
// Now I can avoid all of that silly boilerplate!
string val = _Metadata[metaDataKey].TrimEnd();
}
At any rate, i don't think that such a feature exists, but if it did I would be very pleased indeed. Has anyone tackled this type of problem before? It's looking like I am going to wind up needed some type of extension method in the end...
Unless I'm missing something in your question, this is exactly what you're supposed to be doing. I'm pretty sure every exception includes an overload that takes string message as a parameter. If you want to provide information above and beyond the "default" provided by .NET, you need to set the specific message.
You seem to be doing this the right way to begin with. I would however change the way you check for exceptions:
public string GetMetadata(string metaDataKey)
{
try
{
string val = _Metadata[metaDataKey].TrimEnd();
return val;
}
catch (KeyNotFoundException ex)
{
// or your own custom MetaDataNotFoundException or some such, ie:
// throw new MetaDataNotFoundException(metaDatakey);
throw new KeyNotFoundException(string.Format("There is no metadata that contains the key '{0}'!", metaDataKey));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With