How to capture stack trace?

Sometimes I create an instance of Exception without throwing it (for example, pass it directly to the handler).

 OnException(new AuthorizationException()); 

How to initialize stack trace with current location?

+4
source share
3 answers

You can use the Environment.StackTrace property or use the StackTrace class:

 var stack = new StackTrace(); var data = stack.<whatever you need from it> 

But I just have to add: what you do is very poorly conceptual.

+3
source

In fact, you are asking two different questions (one in the title, the other at the end).

"How to capture a stack trace?"

Just request the static property System.Environment.StackTrace or through new System.Diagnostics.StackTrace(); .

Reading this property does not require the creation of an exception object at all, so perhaps this is all you need.

"How to initialize the stack trace of the Exception object with the current location?"

The exception object StackTrace property is not initialized until you actually throw the exception object.

"The stack trace is created during the creation of the exception. This is different from Java, where the stack trace is created during the construction of the exception object [& hellip;]." - Standard Standard Infrastructure for Public Languages , chap. 18, p. 301.

Since this property is read-only, you cannot initialize it yourself — unless you get your own exception class:

 // don't do that: class ExceptionWithPresetStackTrace : System.Exception { public ExceptionWithPresetStackTrace(string stackTrace) { this.stackTrace = stackTrace; } public override string StackTrace { get { return stackTrace; } } readonly string stackTrace; } 

In combination with the answer to the first question, you can do the following:

 OnException(new ExceptionWithPresetStackTrace(System.Environment.StackTrace)); 

However, this is usually a bad idea, because it allows you to create exception objects that indicate to the developer in any random place (via the StackTrace property), even those where there were virtually no errors. This is misleading and should be avoided.

+3
source
0
source

Source: https://habr.com/ru/post/1395772/


All Articles