I want to get a central place to extract information from an exception, set all the information I need into its message parameter, and then reinstall this information as an exception of the same type.
The best solution would probably be to do it in the place where the exception is finally handled (and its message is logged), but .. I have control over the place that throws the exception, and not over the place that receives the exception and only logs its message content.
Besides this constructive decision and considering that the message is a readonly property, I would (?) Somehow create a new Exception object, is there a way to make the new exception object the same type as the original
Here is my code that does not compile - it stumbles upon a throw line (where I am trying to dynamically drop an object).
public static void RethrowExceptionWithFullDetailInMessage(string msg, Exception ex) { Exception curEx = ex; int cnt = 0; while (curEx != null) { msg += "\r\n"; msg += cnt++ + " ex.message: " + curEx.Message + "\r\n"; msg += "Stack: " + curEx.StackTrace; curEx = curEx.InnerException; } object newEx = Convert.ChangeType(new Exception(msg), ex.GetType()); throw (ex.GetType())newEx; }
it
throw (Exception)newEx;
save type? (It compiles.)
Does Convert.ChangeType set that I get an exception from the correct type?
Andreas Reiff
source share