1

I have a Xamarin Forms app in which I am trying to set up a global exception handler. (.NET Standard 2.1, Microsoft Visual Studio Community 2022 Version 17.2.4 ) I used code from microsoft here.

I am using only the Android platform version of the app.

In AppShell.xaml.cs I have this:

AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(wmsGlobalExceptionHandler);
// Same result with the next line instead of the line above
// currentDomain.UnhandledException += wmsGlobalExceptionHandler;

public void wmsGlobalExceptionHandler(object sender, UnhandledExceptionEventArgs e)
{
Console.WriteLine("pds: wmsGlobalExceptionHandler was hit.");
}

Not sure if AppShell.xaml.cs is the right place for ^ that.

In the MainPage.xaml I have a button (TestButton1) that hits the following method in the MainPageViewModel.cs

public async void TestButton1Clicked()
{
throw new System.Exception("Test Button 1 Clicked");
}

I tap TestButton1, and when the code hits the above line, I press F5 and the System.Exception throws and then a System.NullReferenceException throws and then I get "The application is in break mode" There is nothing in the Output window that indicates the problem, and the Call Stack just says External Code.

When I do the same steps running the app directly on the device, without Visual Studio involved, the app just crashes.

What am I doing wrong to get a global exception handler working in the Xamarin Forms app? Thanks.

Jason
  • 86,222
  • 15
  • 131
  • 146
pdschuller
  • 584
  • 6
  • 26
  • Unfortunately, in my experience, the symptom you describe is quite common when using X-Forms. XF doesn't seem to recover well from exceptions in code executed on UI thread by an event handler. (Which is almost all code, in a typical app.) **1)** VS menu Debug / Windows / Exception Settings - make sure all "Common Language Runtime Exceptions" are checked. When you did F5, it should have stopped on your `throw` line. **2)** Wrap your button handling code with a try-catch, and deal with it in the catch. [OPINION] Global event handler has not been useful for me, when using XF. – ToolmakerSteve Aug 11 '22 at 02:44
  • 1
    I have tried to use your code to test the AppDomain UnhandledException, and I found the `wmsGlobalExceptionHandler` will not hit sometimes. So you can try to add a break point to check it. In addition, the `AppDomain UnhandledException` always crash the application and needs to use the legacyUnhandledExceptionPolicy to stop the crash. But there is no place to use it in the XF. – Liyun Zhang - MSFT Aug 11 '22 at 06:45
  • @ToolmakerSteve Yep, I had your #1 set up already. Thanks for the comments guys. Enlightening. – pdschuller Aug 11 '22 at 12:54

0 Answers0