【转】UWP 捕获全局异常
转自:http://www.cnblogs.com/youngytj/p/4749004.html
异步(async)方法中的异常无法被App的UnhandledException捕获的问题
这是一个比较严重的问题.目前已知很多的做法就是局部try catch来解决这个问题.这样做是很容易导致Process被强制终止然后引起闪退的问题的.
我这里用了一个线程同步模型类解决这个问题.
using System;
using System.Threading;
using Windows.UI.Xaml.Controls; namespace AiJianShu.ExceptionHandler
{
internal class ExceptionHandlingSynchronizationContext : SynchronizationContext
{
/// <summary>
/// 注册事件. 需要在OnLaunched和OnActivated事件中调用
/// </summary>
/// <returns></returns>
public static ExceptionHandlingSynchronizationContext Register()
{
var syncContext = Current;
if (syncContext == null)
throw new InvalidOperationException("Ensure a synchronization context exists before calling this method."); var customSynchronizationContext = syncContext as ExceptionHandlingSynchronizationContext; if (customSynchronizationContext == null)
{
customSynchronizationContext = new ExceptionHandlingSynchronizationContext(syncContext);
SetSynchronizationContext(customSynchronizationContext);
} return customSynchronizationContext;
} /// <summary>
/// 将线程的上下文绑定到特定的Frame上面
/// </summary>
/// <param name="rootFrame"></param>
/// <returns></returns>
public static ExceptionHandlingSynchronizationContext RegisterForFrame(Frame rootFrame)
{
if (rootFrame == null)
throw new ArgumentNullException("rootFrame"); var synchronizationContext = Register(); rootFrame.Navigating += (sender, args) => EnsureContext(synchronizationContext);
rootFrame.Loaded += (sender, args) => EnsureContext(synchronizationContext); return synchronizationContext;
} private static void EnsureContext(SynchronizationContext context)
{
if (Current != context)
SetSynchronizationContext(context);
} private readonly SynchronizationContext _syncContext; public ExceptionHandlingSynchronizationContext(SynchronizationContext syncContext)
{
_syncContext = syncContext;
} public override SynchronizationContext CreateCopy()
{
return new ExceptionHandlingSynchronizationContext(_syncContext.CreateCopy());
} public override void OperationCompleted()
{
_syncContext.OperationCompleted();
} public override void OperationStarted()
{
_syncContext.OperationStarted();
} public override void Post(SendOrPostCallback d, object state)
{
_syncContext.Post(WrapCallback(d), state);
} public override void Send(SendOrPostCallback d, object state)
{
_syncContext.Send(d, state);
} private SendOrPostCallback WrapCallback(SendOrPostCallback sendOrPostCallback)
{
return state =>
{
try
{
sendOrPostCallback(state);
}
catch (Exception ex)
{
if (!HandleException(ex))
throw;
}
};
} private bool HandleException(Exception exception)
{
if (UnhandledException == null)
return false; var exWrapper = new AysncUnhandledExceptionEventArgs
{
Exception = exception
}; UnhandledException(this, exWrapper); #if DEBUG && !DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION
if (System.Diagnostics.Debugger.IsAttached) System.Diagnostics.Debugger.Break();
#endif
return exWrapper.Handled;
} public event EventHandler<AysncUnhandledExceptionEventArgs> UnhandledException;
} public class AysncUnhandledExceptionEventArgs : EventArgs
{
public bool Handled { get; set; }
public Exception Exception { get; set; }
}
}
使用实例:
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending; this.UnhandledException += App_UnhandledException; } private void RegisterExceptionHandlingSynchronizationContext()
{
ExceptionHandlingSynchronizationContext
.Register()
.UnhandledException += SynchronizationContext_UnhandledException;
} private async void App_UnhandledException(object sender, Windows.UI.Xaml.UnhandledExceptionEventArgs e)
{
e.Handled = true; await new MessageDialog("Application Unhandled Exception:\r\n" + e.Exception.Message)
.ShowAsync();
} private async void SynchronizationContext_UnhandledException(object sender, AysncUnhandledExceptionEventArgs e)
{
e.Handled = true; await new MessageDialog("Synchronization Context Unhandled Exception:\r\n" + e.Exception.Message)
.ShowAsync();
} protected override void OnLaunched(LaunchActivatedEventArgs e)
{
RegisterExceptionHandlingSynchronizationContext(); #if DEBUG
if (System.Diagnostics.Debugger.IsAttached)
{
this.DebugSettings.EnableFrameRateCounter = true;
}
#endif Frame rootFrame = Window.Current.Content as Frame; // 不要在窗口已包含内容时重复应用程序初始化,
// 只需确保窗口处于活动状态
if (rootFrame == null)
{
// 创建要充当导航上下文的框架,并导航到第一页
rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: 从之前挂起的应用程序加载状态
} // 将框架放在当前窗口中
Window.Current.Content = rootFrame;
} if (rootFrame.Content == null)
{
// 当导航堆栈尚未还原时,导航到第一页,
// 并通过将所需信息作为导航参数传入来配置
// 参数
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
// 确保当前窗口处于活动状态
Window.Current.Activate();
} protected override void OnActivated(IActivatedEventArgs args)
{
RegisterExceptionHandlingSynchronizationContext();
base.OnActivated(args);
}
【转】UWP 捕获全局异常的更多相关文章
- 在C#代码中应用Log4Net(四)在Winform和Web中捕获全局异常
毕竟人不是神,谁写的程序都会有bug,有了bug不可怕,可怕的是出错了,你却不知道错误在哪里.所以我们需要将应用程序中抛出的所有异常都记录起来,不然出了错,找问题就能要了你的命.下面我们主要讨论的是如 ...
- Android捕获全局异常
Android捕获全局异常 程序避免不了出现bug,导致程序崩溃,为了尽量不影响用户体验,可以全局捕获异常 效果图 异常捕获处理前 异常捕获处理后(将程序重新启动) 捕获异常的工具类 package ...
- SpringBoot捕获全局异常
1.创建GloableExceptionAop类捕获全局异常 package com.cppdy.exception; import org.springframework.web.bind.anno ...
- Android应用捕获全局异常自定义处理
[2016-06-30]最新的全局异常处理DRCrashHandler已经集成在DR_support_lib库中 具体请看: https://coding.net/u/wrcold520/p/DR_s ...
- WebForm 在 Global.asax 中捕获全局异常
/// <summary> /// 捕获全局异常 /// </summary> /// <param name="sender">sender& ...
- C# 捕获全局异常
一.在Winform程序中捕获全局异常 在winfrom中我们需要了解Application对象中的两个事件 ①Application.ThreadException 事件--当UI线程中某个异常未被 ...
- SpringBoot学习笔记(二):SpringBoot访问静态文件、捕获全局异常、集成Thymeleaf、集成JSP
SpringBoot访问静态文件 什么是静态文件? 不需要通过web容器去得到的文件,直接通过路径就能得到的文件,比如项目的css,js,img等文件. 所有的资源文件都应该在src/main/res ...
- C# WinForm捕获全局异常
网上找的C# WinForm全局异常捕获方法,代码如下: static class Program { /// <summary> /// 应用程序的主入口点. /// </summ ...
- express捕获全局异常的三种方法
场景 express的路由里抛出异常后,全局中间件没办法捕获,需要在所有的路由函数里写try catch,这坑爹的逻辑让人每次都要多写n行代码 官方错误捕获中件间代码如下 app.use(functi ...
随机推荐
- Andorid类似Fragment更换布置方法
public void replaceRightView(View v) { int f = LinearLayout.LayoutParams.MATCH_PARENT; LinearLayout. ...
- sql datalength与len区别用法
原文:sql datalength与len区别用法 len ( string_expression )参数:要计算的字符串 len() 函数len 函数返回文本字段中值的长度. sql len() 语 ...
- jQuery弹出窗口完整代码
jQuery弹出窗口完整代码 效果体验:http://keleyi.com/keleyi/phtml/jqtexiao/1.htm 1 <!DOCTYPE html PUBLIC "- ...
- 读书笔记—CLR via C#委托和attribute
前言 这本书这几年零零散散读过两三遍了,作为经典书籍,应该重复读反复读,既然我现在开始写博了,我也准备把以前觉得经典的好书重读细读一遍,并且将笔记整理到博客中,好记性不如烂笔头,同时也在写的过程中也可 ...
- Mysql高级之游标
原文:Mysql高级之游标 什么是游标?select 语句也许一次性会取出来n条语句,那么游标便可以一次取出来select中的一条记录.每取出来一条,便向下移动一次!可以实现很复杂逻辑! 上面还有有一 ...
- 读书笔记—CLR via C#字符串及文本
前言 这本书这几年零零散散读过两三遍了,作为经典书籍,应该重复读反复读,既然我现在开始写博了,我也准备把以前觉得经典的好书重读细读一遍,并且将笔记整理到博客中,好记性不如烂笔头,同时也在写的过程中也可 ...
- 打开Openstack dashboard出现Internal Server Error
最近研究openstack,想把自己遇到的问题记录下来,同时如果有别的朋友也碰到同样问题的时候可以有个参考. 这次的问题是在openstack搭建好之后,dashboard本身是能用的,但是在某一天后 ...
- 【ios开发】ios开发问题集锦
1. ARC forbids explicit message send of'release' 'release' is unavailable: not available inautomatic ...
- nginx 安装启动
[root@localhost ~]# wget http://nginx.org/download/nginx-0.7.67.tar.gz --2010-09-24 14:48:12-- http: ...
- [转]JavaScriptCore by Example
原文:http://www.bignerdranch.com/blog/javascriptcore-example/ JavaScriptCore is not a new framework; i ...