Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write in stacktrace

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?

like image 665
J. Lennon Avatar asked Sep 25 '12 19:09

J. Lennon


3 Answers

Create the exception, and put the parameters in the Data dictionary property. Then throw the exception...

like image 148
erikH Avatar answered Oct 04 '22 01:10

erikH


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.

like image 25
Randolpho Avatar answered Oct 04 '22 01:10

Randolpho


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
}
like image 21
David C Avatar answered Oct 04 '22 00:10

David C