简体   繁体   English

如何在Windows Phone中打印异常?

[英]How to print the exception in Windows Phone?

I am trying to code an app for windows phone 8. I want to print the exception to the screen if I get any. 我正在尝试为Windows Phone 8编写应用程序代码。如果我得到任何内容,我想在屏幕上打印异常。 So here is what I am doing: 所以这就是我在做的事情:

try
            {
               //The code which I want to handle for exception
            }
            catch (Exception e)
            {
                ErrorStatus.Text = e.Message + "\n\n" + e.Source + "\n\n" + e.StackTrace;
            }

where ErrorStatus is my TextBlock. 其中ErrorStatus是我的TextBlock。 However, the only line in my catch block is giving me an exception during the runtime. 但是,我的catch块中唯一的一行是在运行时给出了异常。 The exception is: 例外是:

A first chance exception of type 'System.UnauthorizedAccessException' occurred in System.Windows.ni.dll An exception of type 'System.UnauthorizedAccessException' occurred in System.Windows.ni.dll and wasn't handled before a managed/native boundary

Am I doing something wrong syntactically? 我在语法上做错了吗? I am new to C# programming as well as Windows Phone programming. 我是C#编程以及Windows Phone编程的新手。

Edit: 编辑:

More details of the exception: 异常的更多细节:

System.UnauthorizedAccessException was unhandled by user code
HResult=-2147024891
Message=Invalid cross-thread access.
Source=System.Windows
InnerException: 

You need to show your message from the UI thread: web calls always callback on a background worker thread. 您需要从UI线程显示您的消息:Web调用始终在后台工作线程上回调。 So, you need to call the Dispatcher to get this to run on the UI thread. 因此,您需要调用Dispatcher以使其在UI线程上运行。

Also you can just use Exception.ToString() to show the message content as a string. 您也可以使用Exception.ToString()将消息内容显示为字符串。 This has the advantage of also showing any nested exceptions inside the one you're handling. 这样做的好处是还可以在您正在处理的异常中显示任何嵌套异常。

As a temporary measure try: 作为临时措施尝试:

catch (Exception e)
{
    Deployment.Current.Dispatcher.BeginInvoke(() =>
    {
        ErrorStatus.Text = e.ToString();
    }
}

More permanently you should either fix the issue or log it to a file so you aren't catching exceptions which are masking bugs in your code. 更永久地,您应该修复问题或将其记录到文件中,这样您就不会捕获掩盖代码中的错误的异常。

This is the best way to print out your exception message so that you may know where the problem is: 这是打印出异常消息的最佳方式,以便您可以知道问题所在:

try{}
catch(Exception ex)
{
    await new MessageDialog("Error message:\n\n" + ex.message).ShowAsync();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM