2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

WPF でグローバルエラーハンドリングを実装する

Last updated at Posted at 2023-10-13

環境

Microsoft Visual Studio Community 2022 (64 ビット) - Current
Version 17.7.5

.NET 6

やりたいこと

  • WPF アプリで未処理の例外発生時にロギングなどを一括して実装したい
    • 何も言わずに終了するのを回避する

やってみる

  1. 例外発生時に呼び出すメソッドを実装する
  2. OnStartup() をオーバーライドして上記メソッドを登録する
App.xaml.cs
using System;
using System.Windows;

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        DispatcherUnhandledException += OnUnhandledException;
    }

    private void OnUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
    {
        Exception ex = e.Exception;

        // TODO: エラーログの作成・通知・アプリケーションの終了などの処理を追加します
        MessageBox.Show(ex.Message);
    }
}

たったこれだけで、グローバルエラーハンドリングが実装できます。簡単ですね。

2
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?