I have the following code:
catch(Exception ex) { throw new FatalException("An error occurred while trying to load the XSLT file.", ex); }
This unfortunately just swallows up the Exception. I can fix this by doing the following:
catch(Exception ex) { throw; }
But I would still like to include the custom message for help with event logging.
How do I add this message to the exception without losing any information? (stack trace/debug symbols, etc.)
Throwing an exception is as simple as using the "throw" statement. You then specify the Exception object you wish to throw. Every Exception includes a message which is a human-readable error description. It can often be related to problems with user input, server, backend, etc.
When an exception occurred, if you don't handle it, the program terminates abruptly and the code past the line that caused the exception will not get executed.
The method to choose depends on how often you expect the event to occur. Use exception handling if the event doesn't occur very often, that is, if the event is truly exceptional and indicates an error (such as an unexpected end-of-file). When you use exception handling, less code is executed in normal conditions.
If you just need to add information to the original exception, such as a user-readable message or specific details that will be useful to you in tracking down the error but that won't be useful to the end user, you can make use of the Exception's Data property, which is a key/value pair dictionary.
We use this extensively in order to record information such as the report being executed or file that is being processed so that operations can determine what exactly was happening at the time of the error. The user doesn't need this detail since they are working directly with the cause of the failure.
You could also use this to pass a plain text message that makes sense to the user. The only issue is that you will have to perform some additional work in your logging framework or end-user interface in order to extract the data and make it useful to the consumer.
For example, you could do:
catch (Exception ex) { ex.Data.Add("UserMessage", "An error occurred while trying to load the XSLT file."); throw; }
Then in the client-side code, you could test to see if UserMessage exists and, if so, present it to the user instead of the Exception:
catch (Exception ex) { if (ex.Data.Contains("UserMessage")) { MessageBox.Show(ex.Data["UserMessage"].ToString()); } else { MessageBox.Show(ex.Message); } }
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