Note that there are some explanatory texts on larger screens.

plurals
  1. POCustomize .NET framework generated exception messages?
    text
    copied!<p>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.</p> <pre><code>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; } </code></pre> <p>As you can see, I am essentially producing duplicate code just to use a different (better) message. </p> <p><strong>Edit:</strong><br> What I am looking for, essentially is something like this:</p> <pre><code>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(); } </code></pre> <p>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...</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload