Windows phone stack trace

Strange stack trace on Windows phone 8

I have my app in Windows Phone store and from the reports I can see couple of crashes with following stack trace:

Yes, i know the issue is in InputPage populateLocationList method, but the method is quite complex. Any idea what could cause this? How to debug this since im unable to reproduce the error my self.

And this is my populateLocationList:

1 Answer 1

Barring a bug in the async-await machinery (which is a vanishingly-small-but-nonzero possibility), there are four places in your method that could conceivably result in a NullReferenceException:

  • locationTextBox.Text
  • searchString.Length
  • noLocationsFoundText.Visibility
  • routeLocationsList.ItemsSource

Are you certain that none of these are null? Depending on how the async framework is handling error reporting, I also wouldn’t rule out something blowing up in await GetGeocodeAsync , though the stack trace suggests otherwise.

Incidentally, why are you initializing a List and immediately overwriting it? It’s not the problem here, but looks redundant.

To help you debug, as @devha suggests you can set your debugger to break as soon as a particular exception is thrown. In the ‘Debug’ menu, select ‘Exceptions’, and under CLR Exceptions check NullReferenceException. Now, whenever one of those is thrown while you are debugging, Visual Studio will immediately pause and show you the offending line.

Что такое stack trace, и как с его помощью находить ошибки при разработке приложений?

Иногда при запуске своего приложения я получаю подобную ошибку:

Мне сказали, что это называется «трассировкой стека» или «stack trace». Что такое трассировка? Какую полезную информацию об ошибке в разрабатываемой программе она содержит?

Немного по существу: довольно часто я вижу вопросы, в которых начинающие разработчики, получая ошибку, просто берут трассировки стека и какой-либо случайный фрагмент кода без понимания, что собой представляет трассировка и как с ней работать. Данный вопрос предназначен специально для начинающих разработчиков, которым может понадобиться помощь в понимании ценности трассировки стека вызовов.

1 ответ 1

Простыми словами, трассировка стека – это список методов, которые были вызваны до момента, когда в приложении произошло исключение.

Читайте также:  Дата для установки mac os lion

Простой случай

В указанном примере мы можем точно определить, когда именно произошло исключение. Рассмотрим трассировку стека:

Это пример очень простой трассировки. Если пойти по списку строк вида «at…» с самого начала, мы можем понять, где произошла ошибка. Мы смотрим на верхний вызов функции. В нашем случае, это:

Для отладки этого фрагмента открываем Book.java и смотрим, что находится на строке 16 :

Это означает то, что в приведенном фрагменте кода какая-то переменная (вероятно, title ) имеет значение null .

Пример цепочки исключений

Иногда приложения перехватывают исключение и выбрасывают его в виде другого исключения. Обычно это выглядит так:

Трассировка в этом случае может иметь следующий вид:

В этом случае разница состоит в атрибуте «Caused by» («Чем вызвано»). Иногда исключения могут иметь несколько секций «Caused by». Обычно необходимо найти исходную причину, которой оказывается в самой последней (нижней) секции «Caused by» трассировки. В нашем случае, это:

Аналогично, при подобном исключении необходимо обратиться к строке 22 книги Book.java , чтобы узнать, что вызвало данное исключение – NullPointerException .

Еще один пугающий пример с библиотечным кодом

Как правило, трассировка имеет гораздо более сложный вид, чем в рассмотренных выше случаях. Приведу пример (длинная трассировка, демонстрирующая несколько уровней цепочек исключений):

В этом примере приведен далеко не полный стек вызовов. Что вызывает здесь наибольший интерес, так это поиск функций из нашего кода – из пакета com.example.myproject . В предыдущем примере мы сначала хотели отыскать «первопричину», а именно:

Однако все вызовы методов в данном случае относятся к библиотечному коду. Поэтому мы перейдем к предыдущей секции «Caused by» и найдем первый вызов метода из нашего кода, а именно:

Windows C++ stack trace from a running app

I saw an app, an SVN Visual Studio plugin, that displayed a beautiful readable stack trace, when it crashed.

I would love to add that to my application. How do I provide that? No emailing of the information, just a visual display is enough.

3 Answers 3

The core of the necessary code is StackWalk64 . To get much from that, you’ll also want/need to get symbol names with SymGetSymFromAddr64 (which requires SymLoadModule64 ) and (probably) SymGetLineFromAddr64 and GetThreadContext . If the target was written in C++, you’ll probably also want to use UnDecorateSymbolName . Along with those you’ll need a few ancillaries like SymInitialize , SymCleanup , and probably SymSetOptions .

Читайте также:  Code writer windows 10 как пользоваться

Here’s a fairly minimal demo. The stack dump it produces is more utilitarian than beautiful, but presumably with the basics of doing the stack trace, you can display the results as you see fit:

I modified Jerry Coffin’s code as you see below. Modifications:

A. I was always missing the most important frame of all: the line that actually triggered the exception. Turns out this was because the «do» loop was moving to the next frame at the top instead of at the bottom.

B. I removed the threading stuff.

C. I simplified a few bits.

You should cut the «WinMain()» function at the bottom and instead put the __try .. __except stuff in your own ‘main/WinMain’ function. Also replace ‘YourMessage’ with your own function to display a message box or email it or whatever.

The symbolic information is stored inside a .pdb file, not the .exe. You need to give your users your .pdb file, and you need to ensure that their process can find it. See the string inside the code below — replace this with a folder that will work on the users’ machine, or NULL — NULL means it will search in the process’s current working directory. The .pdb file must have the exact same name on the users’ computer as it had when you ran your compiler — to configure this to something different, see «Properties > Linker > Debugging > Generate Program Database File».

How to Log Full Stack Trace with Winston 3?

My logger is set up like:

Then I am logging out some error like this:

How is it possible to log the full stack trace for errors to via the error transport? I tried passing in the err.stack and it came out as undefined.

6 Answers 6

For winston version 3.2.0+ , following will add stacktrace to log output:

You can write a formatter to pass error.stack to log.

(the output will depend on your configuration)

UPDATE 1/14/2021 — This no longer works in newer versions of Winston.

Original Answer

@Ming’s answer got me partly there, but to have a string description with the error, this is how I got full stack tracing working on ours:

Here is another take for Winston 3.2.

Nowadays Winston comes with a built-in stacktrace formatter, but it does not seem to trigger if the same formatter has winston.format.simple() combined. Thus, you need use winston.format.printf instead as by the answer from Kirai Mali. I could not figure out how to configure both winston.format.errors() and winston.format.simple() in the same configuration.

Читайте также:  Как отключит клавишу windows

Based on the current Winston README example and answers above, here is my configuration that uses JSON format logfiles, but for the local development console it still gives colored log lines and good stack traces.

Here is my logger configuration. Added errors(< stack: true >) , thanks to Murli Prajapati ans and small trick in printf function. My winston version is 3.2.1 .

I am using this same configuration in express-winston and for general log also.

How do I find the stack trace in Visual Studio?

I ask because I couldn’t find the stack trace in Visual Studio, while debugging an exception that occurred.

7 Answers 7

While debugging, Go to Debug -> Windows -> Call Stack

While debugging, when you hit a break-point.

The default shortcut key is Ctrl-Alt-C.

Do you mean finding a stack trace of the thrown exception location? That’s either Debug/Exceptions, or better — Ctrl-Alt-E. Set filters for the exceptions you want to break on.

There’s even a way to reconstruct the thrower stack after the exception was caught, but it’s really unpleasant. Much, much easier to set a break on the throw.

Using the Call Stack Window

To open the Call Stack window in Visual Studio, from the Debug menu, choose Windows>Call Stack. To set the local context to a particular row in the stack trace display, double click the first column of the row.

Consider this as the current update (Windows 10 (Version 1803) and Visual Studio 2017): I was unable to view the stack trace window and did find an option/menu item to view it. On investigating further, it seems this feature is not available on Windows 10. For further information please refer:

Copied from the above link: «This feature is not available in Windows 10, version 1507 and later versions of the WDK.»

For Visual Studio 2019, the shortcut (while debugging and stopped at a breakpoint) is:

Ctrl + Alt + C and now you can also use Ctrl + L

The screenshot is pretty old. Here is one for Visual Studio 2019 (under the debug menu):

Оцените статью