2012/05/28

WPFで未処理の例外を一括処理

アプリケーション開発の定番の例外一括処理。
WPF も Windows Forms 時代とたいして変わらないね。
using System;
using System.Windows;
using System.Windows.Threading;
namespace MktSys.UI.Sample
{
/// <summary>
/// App.xaml の相互作用ロジック
/// </summary>
public partial class App : Application
{
/// <summary>
/// 例外発生時のエラーコード
/// </summary>
private const int ERROR_EXIT_CODE = 1;
/// <summary>
/// アプリケーション開始時の処理。
/// </summary>
/// <param name="sender">イベント発生元</param>
/// <param name="e">イベント引数</param>
private void Application_Startup(object sender, StartupEventArgs e)
{
this.RegisterErrorHandler();
}
/// <summary>
/// 例外発生時に補足するための処理を登録する。
/// </summary>
private void RegisterErrorHandler()
{
this.DispatcherUnhandledException +=
new DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
}
/// <summary>
/// UIスレッドにて例外が発生した時の処理。
/// </summary>
/// <param name="sender">発生元</param>
/// <param name="e">例外情報</param>
private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
e.Handled = true;
var result = this.ShowErrorInfo(e.Exception);
if (result == MessageBoxResult.OK)
{
this.Shutdown(ERROR_EXIT_CODE);
}
}
/// <summary>
/// UIスレッド以外で例外が発生した時の処理。
/// </summary>
/// <param name="sender">発生元</param>
/// <param name="e">例外情報</param>
private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
var result = this.ShowErrorInfo(e.ExceptionObject as Exception);
if (result == MessageBoxResult.OK)
{
Environment.Exit(ERROR_EXIT_CODE);
}
}
/// <summary>
/// 指定の例外情報をメッセージボックスとして表示します。
/// </summary>
/// <param name="ex">例外</param>
/// <returns>メッセージボックス結果</returns>
private MessageBoxResult ShowErrorInfo(Exception ex)
{
return MessageBox.Show(
String.Format("{0}\n{1}", ex.Message, ex.StackTrace),
"エラーが発生しました。",
MessageBoxButton.OK,
MessageBoxImage.Stop);
}
}
}
view raw gistfile1.cs hosted with ❤ by GitHub
DispatcherUnhandledException はコードビハインドではなく、App.xaml に記述することもできるけど、UIスレッドで発生した時の DispatcherUnhandledException と UIスレッド以外で発生した時の UnhandledException はセットで考えるべきだと思うので、見通しが良いように一括で設定するようにしてる。

0 件のコメント :

コメントを投稿