Reputation: 3361
Can I throw some text in the stack trace?
My application already has a grip on the exceptions thrown. But would like to have some more information on some methods (parameters).
The idea was to do something like
StackTrace.Insert (0, "argument:" + test);
I know this is not cool, but is it possible?
Upvotes: 8
Views: 4845
Reputation: 2346
Create the exception, and put the parameters in the Data dictionary property. Then throw the exception...
Upvotes: 13
Reputation: 56448
Just to add to @erikH's excellent answer:
In addition to using the Data
property, if you need additional data available up the exception chain, you can do so by means of a custom exception. In addition to the meta-information that a custom type can provide (a CommunicationException
might mean a problem with I/O, an InvalidStateException
might mean the program encountered an invalid state, and so forth) you can add additional information to the exception in the form of custom fields. Custom fields are especially useful when you need type safety that the Data
property doesn't provide.
Upvotes: 5
Reputation: 3810
By definition, the stack trace is an output of the active stack frames at the current execution point in a program, generally accessed via an Exception.
@David Yaw gave you the correct way to add additional information to a stack trace, as it bubbles up the exception stack. To rephrase, you should only be adding your custom data to the stack trace, when it is the result of an exception.
Either create some centrally accessible List collection to store logging data in, or use proper try/catch with exception bubbling as David recommended.
for example.
try
{
doSomethingThatMightFailAndThrowAnException();
}
catch (Exception ex)
{
throw new Exception("Here is some custom data to add to the trace...",ex);
// Notice adding the ex as the second parameter preserves the original exception trace
}
Upvotes: 2