Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customize .NET framework generated exception messages?

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...

like image 399
A.R. Avatar asked Dec 10 '25 09:12

A.R.


2 Answers

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.

like image 66
AllenG Avatar answered Dec 12 '25 23:12

AllenG


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));
    }
}
like image 31
Chris Walsh Avatar answered Dec 12 '25 21:12

Chris Walsh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!