I would like to show an apologetic message and close my WPF application if any request to Elasticsearch failes. There are a lot of requests in the app so the most convinient way I think is to throw an exception in OnRequestCompleted callback if something goes wrong and then handle it globally. But each of 4 ways of handling unhandled exceptions listed here do nothing and the app just crashes. Here is the simpliest example. What's wrong there?
App.xaml
<Application x:Class="WPF_Elasticsearch_2._3.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DispatcherUnhandledException="App_OnDispatcherUnhandledException"
StartupUri="MainWindow.xaml">
</Application>
App.xaml.cs
using System;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using Nest;
namespace WPF_Elasticsearch_2._3
{
public partial class App : Application
{
public static IElasticClient ElasticClient { get; private set; }
public App()
{
AppDomain.CurrentDomain.UnhandledException += App_OnUnhandledException;
TaskScheduler.UnobservedTaskException += App_OnUnobservedTaskException;
Dispatcher.UnhandledException += App_OnDispatcherUnhandledException;
var connectionSettings = new ConnectionSettings(new Uri("http://localhost:9200"))
.OnRequestCompleted(callDetails =>
{
if (!callDetails.Success)
throw new Exception("Unsuccessful request!");
});
ElasticClient = new ElasticClient(connectionSettings);
}
private void App_OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
MessageBox.Show(e.Exception.Message);
e.Handled = true;
Shutdown(-1);
}
private void App_OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
MessageBox.Show(((Exception)e.ExceptionObject).Message);
Shutdown(-1);
}
private void App_OnUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
{
MessageBox.Show(e.Exception.Message);
e.SetObserved();
Shutdown(-1);
}
}
}
MainWindow.xaml
<Window x:Class="WPF_Elasticsearch_2._3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="MainWindow" Height="240" Width="320">
<Button Click="ButtonBase_OnClick">Make request</Button>
</Window>
MainWindow.xaml.cs
using System.Windows;
namespace WPF_Elasticsearch_2._3
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
App.ElasticClient.Search<object>(descriptor => descriptor
.Index("test-index")
.Type("test-type"));
}
}
}