-
-
Save mattjohnsonpint/7b385b7a2da7059c4a16562bc5ddb3b7 to your computer and use it in GitHub Desktop.
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 | |
} | |
} |
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.
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;
}
Can't highlight this enough...
Also don't forget to add args.handled = true before the invoke in the Android unhandled exception section.
Can't highlight this enough too ...
Also don't forget to add
args.Handled = true
before the invoke in the WINDOWS unhandled exception section.
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.
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)
For handling exceptions in the Android space this would be a good extension. This catches errors outside the .net space too (e.g. when using 3rd party libraries)
Java.Lang.Thread.DefaultUncaughtExceptionHandler = new CustomUncaughtExceptionHandler(e =>
UnhandledException?.Invoke(null, new UnhandledExceptionEventArgs(e, true)));
public class CustomUncaughtExceptionHandler(Action<Throwable> callback)
: Java.Lang.Object, Thread.IUncaughtExceptionHandler
{
public void UncaughtException(Thread t, Throwable e)
{
callback(e);
}
}
Java.Lang.Thread.DefaultUncaughtExceptionHandler = new CustomUncaughtExceptionHandler(e => UnhandledException?.Invoke(null, new UnhandledExceptionEventArgs(e, true)));
Hi @Danielku15,
Thank you for sharing.
Can you advise how to implement this?
I've updated it here (Beware execution/throw can be delayed for the task scheduler ;)
https://gist.github.com/myrup/43ee8038e0fd6ef4d31cbdd67449a997