Understanding End of stack trace comment in .NET stack traces - c#

I'm trying to correctly read stack traces generated by ASP.NET Core. I don't have a problem finding the cause of an exception. But I see the comment --- End of stack trace from previous location --- over and over:
Maybe I misunderstood something fundamental about how stack traces are generated. But to my knowledge, the --- End of stack trace ... string is added when using ExceptionDispatchInfo to rethrow errors but maintaining the original stack trace:
ExceptionDispatchInfo.Capture(e).Throw();
(Sort of a hybrid between throw and throw e)
When looking at the ASP.NET Core source code, it looks to just throw exceptions normally. Can anyone explain why the stack trace is formatted as it is?

You wrote:
When looking at the ASP.NET Core source code, it looks to just throw exceptions normally.
But if you look at the places you have in the provided stack trace then you'll see ExceptionDispatchInfo.Capture(e).Throw().
E.g. in ResourceInvoker.InvokeNextResourceFilter:
catch (Exception exception)
{
_resourceExecutedContext = new ResourceExecutedContextSealed(_resourceExecutingContext!, _filters)
{
ExceptionDispatchInfo = ExceptionDispatchInfo.Capture(exception),
};
}
The reason for using ExceptionDispatchInfo.Capture() is well explained in What's the point of passing ExceptionDispatchInfo around instead of just the Exception?

Related

how to properly format stack trace information in asp.net core

I have asp.net core's layered architecture something like code below.
and the main function (API controller) is calling the GrandParent method and controller function also has the try-catch block. for example, an exception occurs in GetNumber function. the exception will bubble-up to the controller. Now if i see the stack trace i can see the trace from Controller->Grandparent->Parent->GetNumber.
is there a way to beautify this stack trace in a way that can tell me this entire stack of calls with just their function names and line number where the original exception occurred, so that I can simply log that formatted beautified information instead of logging the original stack trace?
Is there something Asp.net core gives out of the box for such a problem?
Try something like (i dont know how exactly you want format those)
StackTrace stackTrace = new StackTrace();
stackTrace.GetFrames().Select(f => $"{f.GetMethod()} {f.GetFileLineNumber()}");

c# object reference not set to an instance of an object (no mention of null reference in stack trace)

I am getting a "Object reference not set to an instance of an object" error when running my windows service in Release mode (please note, as you can see from my stack trace, it doesn't mention anything to do with a NullReference which is confusing me more). Each time i run this in debug mode, the code works beautifully, but as soon as i build it to release and start it on the server, it fails with the Object reference error. See below for my stack trace and then below that for my code;
=================================================================================
Error Message: [EventQueueBulkProcessingHandler] Failed to process events
Stack Trace:
Error Message (INNER EXCEPTION LEVEL 1): Object reference not set to an instance of an object.
Stack Trace (INNER EXCEPTION LEVEL 1):
at Voicebox.EventTriggers.Processing.Preparation.EventContactsFilter.Filter(ContactsModel contacts, ContactsFilterModel contactsFilterModel, Int32 clientId) in D:\Websites\VoiceboxTest\Voicebox\VoiceBox.EventTriggers\Processing\Preparation\EventContactsFilter.cs:line 24
at Voicebox.EventTriggers.Processing.Preparation.TriggerActionDetailsBuilder.CreateTriggerActionDetails(Trigger trigger, ITriggerEvent triggerEvent) in D:\Websites\VoiceboxTest\Voicebox\VoiceBox.EventTriggers\Processing\Preparation\TriggerActionDetailsBuilder.cs:line 48
at Voicebox.EventTriggers.Processing.Handlers.UserEventsHandler.<>c__DisplayClass6_0.<MapEventsToTriggers>b__0(Trigger t, ITriggerEvent e) in D:\Websites\VoiceboxTest\Voicebox\VoiceBox.EventTriggers\Processing\Handlers\UserEventsHandler.cs:line 62
at Voicebox.EventTriggers.Helpers.PermutationsHelper.<>c__DisplayClass0_1`3.<Permutations>b__1(TB b) in D:\Websites\VoiceboxTest\Voicebox\VoiceBox.EventTriggers\Helpers\PermutationsHelper.cs:line 11
at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
at System.Linq.Enumerable.<SelectManyIterator>d__17`2.MoveNext()
at System.Linq.Enumerable.WhereEnumerableIterator`1.MoveNext()
at System.Linq.Enumerable.<SelectManyIterator>d__17`2.MoveNext()
at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at Voicebox.EventTriggers.Processing.Handlers.UserEventsHandler.<HandleAsync>d__5.MoveNext() in D:\Websites\VoiceboxTest\Voicebox\VoiceBox.EventTriggers\Processing\Handlers\UserEventsHandler.cs:line 37
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Voicebox.EventTriggers.Processing.EventQueueBulkProcessingHandler.<ProcessEventsGrouppedByClient>d__8.MoveNext() in D:\Websites\VoiceboxTest\Voicebox\VoiceBox.EventTriggers\Processing\EventQueueBulkProcessingHandler.cs:line 107
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Voicebox.EventTriggers.Processing.EventQueueBulkProcessingHandler.<ProcessInternal>d__6.MoveNext() in D:\Websites\VoiceboxTest\Voicebox\VoiceBox.EventTriggers\Processing\EventQueueBulkProcessingHandler.cs:line 52
=================================================================================
So going off of the above stack trace, it says the issue is in the file EventContactsFilter at line 24. This is where its making no sense to me as this is the initialisation of a List. See below code;
// this is the line 24 which the stack trace points too
List<string> filterExpressions = new List<string>();
foreach (var model in contactsFilterModel.Criteria)
{
string fieldName = GetFieldName(contacts.ListId, model.FieldID, clientId);
FieldType fieldType = GetFieldType(model);
FilterExpression FilterExpression = ExpressionBuilder.GetFilterExpression(fieldName, model, fieldType);
var expression = FilterExpression.sqlExpression;
filterExpressions.Add(expression);
}
So as you can see, the error is being thrown on the creation of a new list, and after many many hours or searching the web, ive not been able to find out what may be causing this. If anyone is able to help, i would be forever in your debt!!
I'm not really convinced that the problem is the List<string> declaration. Please use a try-catch around that declaration, and see what the actual error message is.
My intuition says the problem it's not there. Maybe something above,or under that line. My guess that foreach. Either way, try-catch that code :)

Preserving stack trace when rethrowing exceptions in Silverlight

I need to rethrow an Exception that was caught and stored elsewhere without losing the stack trace information about when the Exception was first caught/stored. My code looks something like this:
public void Test()
{
int someParameter = 12;
ExecuteSomeAsyncMethod(someParameter, CallbackMethod);
}
public void CallbackMethod(object result, Exception error)
{
//Check for exceptions that were previously caught and passed to us
if(error != null)
//Throwing like this will lose the stack trace already in Exception
//We'd like to be able to rethrow it without overwriting the stack trace
throw error;
//Success case: Process 'result'...etc...
}
I've seen solutions to this problem that use reflection (for example here and here) or use Serialization (for example here) but none of those will work for me in Silverlight (private reflection is not allowed and the classes/methods used in the serialization approach don't exist in Silverlight).
Is there any way to preserve the stack trace that works in Silverlight?
Throw a new exception with the exception as inner exception:
throw new ApplcationException("Error message", error);
The inner exception will keep it's stack trace.
You can either use
catch(Exeption)
{
throw;
}
or
catch(Exception e)
{
throw new Exception(e);
}
Both will keep the stack trace. The first solution seems not to be possible in your example, but the second should work.
Of cause in your case you would throw the parameter error instead of e.

Problem with Environment.StackTrace

On a thread that is processing new data in the system, if the data is invalid I write a message in the event log, containing the Environment.StackTrace information.
Writing in the event log throws an exception with no text message
Message:
CallStack - at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
at System.Environment.get_StackTrace()
at <my method that writes in the event log>
Any ideas why this happens?
EDIT: I am interested in what can cause the Environment.StackTrace to throw exception in general, so that i can understand what is happening in my case
#anchandra I don't know if you have figured this out since, as this is now 4 years old.
However I would like to add as I just stumbled upon this myself.
So, why does Environment.StackTrace throws an exception?
First the most uninteresting answer:
As you can see in the MSDN reference to the property, it can throw an ArgumentOutOfRangeException if "The requested stack trace information is out of range.", note also that the executing context must have System.Security.Permissions.EnvironmentPermission.
Now what stumped me for a second:
It does NOT throw an exception! Yes, that is what was happening to me, it actually returned me a Stack Trace that started listing the call to Environment.StackTrace like "at System.Environment.get_StackTrace()" then it showed all the other calling methods.
Because I was logging this into an audit log, if you look at it you assume there is an exception occurring at the last frame of the stack, but that's not true, I was just happening to request a Stack Trace at that point and stick it in my error log, very dumb once I realized this.
You need to capture the stacktrace before moving onto a separate thread.
Stacktrace will only show you the frames up to the root of the thread.

Stack call in Exception Handling

According to the design guideline the catching exception should start from more specification exception to System.Exception.
like :
try
{
}
catch(IOException IOEx)
{
}
catch(ArrayIndexOutOfRangeException AIE)
{
}
.....
catch(Exception ex)
{
}
I heard that CLR tracks the stack to trace the exception one by one to find the matching one(if an error occur).
As stack is "Last in first out" in nature won't CLR look in
reverse order ? ( i.e Exception .. ArrayIndexOutOfRangeException .. IOException)
No - the stack in this case is the call stack, so if it doesn't find a handler in the current method, it will move up the stack to look for a handler. Within a particular method however, handlers are tested in the order they are specified.

Categories

Resources