Skip to content

Instantly share code, notes, and snippets.

@mattjohnsonpint
Last active July 25, 2024 17:35
Show Gist options
  • Save mattjohnsonpint/7b385b7a2da7059c4a16562bc5ddb3b7 to your computer and use it in GitHub Desktop.
Save mattjohnsonpint/7b385b7a2da7059c4a16562bc5ddb3b7 to your computer and use it in GitHub Desktop.
Unified global Unhandled Exception event for .NET MAUI
MIT License
Copyright (c) 2022 Matt Johnson-Pint
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
public static class MauiExceptions
{
#if WINDOWS
private static Exception _lastFirstChanceException;
#endif
// We'll route all unhandled exceptions through this one event.
public static event UnhandledExceptionEventHandler UnhandledException;
static MauiExceptions()
{
// This is the normal event expected, and should still be used.
// It will fire for exceptions from iOS and Mac Catalyst,
// and for exceptions on background threads from WinUI 3.
AppDomain.CurrentDomain.UnhandledException += (sender, args) =>
{
UnhandledException?.Invoke(sender, args);
};
#if IOS || MACCATALYST
// For iOS and Mac Catalyst
// Exceptions will flow through AppDomain.CurrentDomain.UnhandledException,
// but we need to set UnwindNativeCode to get it to work correctly.
//
// See: https://github.com/xamarin/xamarin-macios/issues/15252
ObjCRuntime.Runtime.MarshalManagedException += (_, args) =>
{
args.ExceptionMode = ObjCRuntime.MarshalManagedExceptionMode.UnwindNativeCode;
};
#elif ANDROID
// For Android:
// All exceptions will flow through Android.Runtime.AndroidEnvironment.UnhandledExceptionRaiser,
// and NOT through AppDomain.CurrentDomain.UnhandledException
Android.Runtime.AndroidEnvironment.UnhandledExceptionRaiser += (sender, args) =>
{
UnhandledException?.Invoke(sender, new UnhandledExceptionEventArgs(args.Exception, true));
};
#elif WINDOWS
// For WinUI 3:
//
// * Exceptions on background threads are caught by AppDomain.CurrentDomain.UnhandledException,
// not by Microsoft.UI.Xaml.Application.Current.UnhandledException
// See: https://github.com/microsoft/microsoft-ui-xaml/issues/5221
//
// * Exceptions caught by Microsoft.UI.Xaml.Application.Current.UnhandledException have details removed,
// but that can be worked around by saved by trapping first chance exceptions
// See: https://github.com/microsoft/microsoft-ui-xaml/issues/7160
//
AppDomain.CurrentDomain.FirstChanceException += (_, args) =>
{
_lastFirstChanceException = args.Exception;
};
Microsoft.UI.Xaml.Application.Current.UnhandledException += (sender, args) =>
{
var exception = args.Exception;
if (exception.StackTrace is null)
{
exception = _lastFirstChanceException;
}
UnhandledException?.Invoke(sender, new UnhandledExceptionEventArgs(exception, true));
};
#endif
}
}
@forlayo
Copy link

forlayo commented Jun 2, 2023

Where is the best place to init this ?

@myrup
Copy link

myrup commented Jun 4, 2023

I would add

  TaskScheduler.UnobservedTaskException += (sender, args) => {
                UnhandledException?.Invoke(sender, new UnhandledExceptionEventArgs(args.Exception, false));
            };

to catch

        Task.Run(() => throw new Exception("Handle me"));

Edit: Beware execution/throw can be delayed when testing ;)

@grenzi
Copy link

grenzi commented Aug 27, 2023

Wow. This is really really useful. Thanks!

@axa88
Copy link

axa88 commented Sep 21, 2023

Where is the best place to init this ?

Building on this question, might someone be so kind to suggest optimal usage...

@mwardell-Katmai
Copy link

Where should I put this statement? in my MAUI App?

TaskScheduler.UnobservedTaskException += (sender, args) => {
UnhandledException?.Invoke(sender, new UnhandledExceptionEventArgs(args.Exception, false));
};

@myrup
Copy link

myrup commented Oct 2, 2023

Where should I put this statement? in my MAUI App?

TaskScheduler.UnobservedTaskException += (sender, args) => { UnhandledException?.Invoke(sender, new UnhandledExceptionEventArgs(args.Exception, false)); };

I've updated it here (Beware execution/throw can be delayed for the task scheduler ;)
https://gist.github.com/myrup/43ee8038e0fd6ef4d31cbdd67449a997

@Wandtket
Copy link

Wandtket commented Oct 2, 2023

For anyone who might be confused when first attempting to get universal error handling, at least for Android, the Error handling happens when the debugger IS NOT attached. Also don't forget to add args.handled = true before the invoke in the Android unhandled exception section.

@dpmaddy
Copy link

dpmaddy commented Oct 3, 2023

After some testing, I can't seem to get the handler (and by extension, UnhandledException event) to be called on iOS. My code is a carbon copy of the gist, but it doesn't seem to want to play nicely :/

Has anyone managed to get this up and running in a .NET 7 Maui App for iOS? Any tips or pointers would be greatly appreciated :)

FYI: I setup my event listener inside App.xaml.cs like so,

MauiExceptions.UnhandledException += (sender, args) =>
{
    _logger.LogCritical(e.ExceptionObject as Exception, "App failed to handle exception");
    throw (Exception)e.ExceptionObject;
}

@DP-Technology-LLC
Copy link

Can't highlight this enough...

Also don't forget to add args.handled = true before the invoke in the Android unhandled exception section.

@TomasPecinka
Copy link

TomasPecinka commented Jun 19, 2024

Can't highlight this enough too ...

Also don't forget to add args.Handled = true before the invoke in the WINDOWS unhandled exception section.

@janseris
Copy link

janseris commented Jul 25, 2024

AppDomain.CurrentDomain.UnhandledException
still executes for Android, the comment is not correct.
It happens at least when using Debug build with debugger attached.
The application however crashes before the handling code executes but that is expected as it is terminating.
obrazek

The exception is raised using the following command:

private async void ThrowException()
{
    // To test this use case properly, run the app without attached debugger.
    throw new Exception("Unhandled exception (should be handled by global exception handler).");
}

args.IsTerminating returns true

Without attached debugger this does not happen (probably)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment