Skip to content

Commit

Permalink
Add a handler for unhandled exceptions that crash the program.
Browse files Browse the repository at this point in the history
Save the results to a log that can be sent back to the programmer.
  • Loading branch information
Kinematics committed Oct 27, 2015
1 parent 0fa541f commit a6b6e6e
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions NetTally/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
Expand Down Expand Up @@ -56,6 +57,9 @@ public string MyTitle
/// </summary>
public MainWindow()
{
// Set up an event handler for any otherwise unhandled exceptions in the code.
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

InitializeComponent();

// Set tally vars
Expand Down Expand Up @@ -94,6 +98,29 @@ public MainWindow()
MyTitle = $"{product.Product} - {version.InformationalVersion}";
}

/// <summary>
/// Unhandled exception handler. If an unhandled exception crashes the program, save
/// the stack trace to a log file.
/// </summary>
/// <param name="sender">The AppDomain.</param>
/// <param name="e">The details of the unhandled exception.</param>
private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Exception ex = (Exception)e.ExceptionObject;

// print out the exception stack trace to a log
string output =
$"Message is: {ex.Message}\n\n" +
$"Stack Trace is:\n{ex.StackTrace}\n";

string tempFile = Path.GetTempFileName();

File.WriteAllText(tempFile, output);

// Let the user know where the temp file was written.
MessageBox.Show($"Error written to:\n{tempFile}", "Unhandled exception log written", MessageBoxButton.OK, MessageBoxImage.Error);
}

/// <summary>
/// When the program closes, save the current list of quests.
/// </summary>
Expand Down

0 comments on commit a6b6e6e

Please sign in to comment.