Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

App.UnhandledException doesn't catch exceptions from other threads. #5221

Closed
Tracked by #5535
artkat opened this issue Jun 19, 2021 · 38 comments
Closed
Tracked by #5535

App.UnhandledException doesn't catch exceptions from other threads. #5221

artkat opened this issue Jun 19, 2021 · 38 comments
Assignees
Labels
area-Application area-ErrorHandling Issues related to error reporting and debugging bug Something isn't working Crash whenever user reports a crash or app freeze needs-triage Issue needs to be triaged by the area owners product-winui3 WinUI 3 issues v0.8 Issues introduced in the Project Reunion 0.8 prerelease
Milestone

Comments

@artkat
Copy link

artkat commented Jun 19, 2021

Describe the bug
Unable to catch UnhandledException (at app level) when the exception originates from async Task.

Steps to reproduce the bug

  1. Create new WinUI3 project
  2. In App.cs handle UnhandledException:
public App()
        {
            this.InitializeComponent();
            this.UnhandledException += App_UnhandledException;
        }


        private void App_UnhandledException(object sender, Microsoft.UI.Xaml.UnhandledExceptionEventArgs e)
        {
            Debug.WriteLine("WinUI App Crashed");
        }
  1. In MainWindow.cs add a button with code-behind that will throw a devide-by-zero exception from an Async method:
private async void myButton_Click(object sender, RoutedEventArgs e)
        {
            int t = await Task.Run(() =>
            {
                var x = 0;
                var y = 3 / x;
                return y;
            });
        }

Expected behavior
Would expect the App_UnhandledException to 'handle' this exception.

Screenshots
image

Version Info
WinUI 0.8.0-preview
Windows 10

NuGet package version:
Microsoft.ProjectReunion (0.8.0-preview)
Microsoft.ProjectReunion.Foundation (0.8.0-preview)
Microsoft.ProjectReunion.WinUI (0.8.0-preview)

Windows app type:

UWP Win32
No Yes
Windows 10 version Saw the problem?
Insider Build (xxxxx)
October 2020 Update (19042) Yes
May 2020 Update (19041)
November 2019 Update (18363)
May 2019 Update (18362)
October 2018 Update (17763)
April 2018 Update (17134)
Fall Creators Update (16299)
Creators Update (15063)
Device form factor Saw the problem?
Desktop Yes
Xbox
Surface Hub
IoT

Additional context
GitHub example with 2 'identical' projects, one UWP (WinUI2) and one WinUI3, to show the difference in behavior between the two.
https://github.com/artkat/CrashingApp

@ghost ghost added the needs-triage Issue needs to be triaged by the area owners label Jun 19, 2021
@StephenLPeters
Copy link
Contributor

@chrisglein I think the addition context implies that this is a winui3 regression. I'm a bit surprised that Application.UnhandledException could catch off thread exceptions though, I thought this was designed for UI thread exceptions (although the name certainly implies all exceptions)

@Marv51
Copy link
Contributor

Marv51 commented Jun 23, 2021

Is CoreApplication.UnhandledErrorDetected the more relevant event for this?

@artkat
Copy link
Author

artkat commented Jun 25, 2021

@chrisglein I think the addition context implies that this is a winui3 regression. I'm a bit surprised that Application.UnhandledException could catch off thread exceptions though, I thought this was designed for UI thread exceptions (although the name certainly implies all exceptions)

In UWP this was often used to handle (read: log) fatal crashes.
AppCenter framework is also unable to catch fatal WinUI3 crashes.
Any idea how else how to log them?

@chrisglein chrisglein added bug Something isn't working v0.8 Issues introduced in the Project Reunion 0.8 prerelease area-Application and removed needs-triage Issue needs to be triaged by the area owners labels Sep 9, 2021
@chrisglein
Copy link
Member

Still repros on WinAppSDK 8.2.
Confirmed this does get caught on UWP but doesn't in WinUI3, so this is for sure a regression (or not yet implemented).

@Panchus
Copy link

Panchus commented Feb 7, 2022

Windows.ApplicationModel.Core.CoreApplication.UnhandledErrorDetected and Application.UnhandledException works for me on a WinUI 1.0 .Net 6 application, but only on synchronous operations, they fail to catch even the same kind of exceptions thrown in async methods.
Any idea or alternative to do this or I am doing something wrong?

@d2dyno1
Copy link

d2dyno1 commented Mar 5, 2022

Windows.ApplicationModel.Core.CoreApplication.UnhandledErrorDetected and Application.UnhandledException works for me on a WinUI 1.0 .Net 6 application, but only on synchronous operations, they fail to catch even the same kind of exceptions thrown in async methods. Any idea or alternative to do this or I am doing something wrong?

You might be interested in TaskScheduler.UnobservedTaskException @Panchus

@Panchus
Copy link

Panchus commented Mar 6, 2022

Windows.ApplicationModel.Core.CoreApplication.UnhandledErrorDetected and Application.UnhandledException works for me on a WinUI 1.0 .Net 6 application, but only on synchronous operations, they fail to catch even the same kind of exceptions thrown in async methods. Any idea or alternative to do this or I am doing something wrong?

You might be interested in TaskScheduler.UnobservedTaskException @Panchus

I tried that, but in only triggers when you dont await Tasks, this isn't what I want
In any case I know now that there's no way to do this since they are essentially different threads and therefore every async method must catch their own exceptions
Thanks anyways!

@knightmeister
Copy link

Really need a neat way to be able to catch unhandled exceptions, for a few reasons:

  1. analytics (i.e. app center)
  2. display a helpful message to the user

Nothing is more jarring than just having an app disappear.

@sjb-sjb
Copy link

sjb-sjb commented May 17, 2022

Maybe there is a way to do this by replacing the synchronization context? @StephenCleary maybe?

@StephenCleary
Copy link

Seems like they already have a SynchronizationContext, so it's probably just a matter of catching the exception at the top level in that context and raising the top-level event. (Exceptions from async void methods are raised directly on the SynchronizationContext that was current at the time the method started executing).

@artkat
Copy link
Author

artkat commented May 26, 2022

This bug has been reported nearly a year ago.
Still, no one has been assigned to fix it.
I'm disappointed, frustrated, annoyed, and honestly quite pissed that this is the way Microsoft handles this project.

@knightmeister
Copy link

This bug has been reported nearly a year ago. Still, no one has been assigned to fix it. I'm disappointed, frustrated, annoyed, and honestly quite pissed that this is the way Microsoft handles this project.

It really feels like WinUI is enormously underresourced. There are trivial bugs, and real show stopping bugs that have been kicking around for a loooong time. I'm hopeful this is going to change in the near future because I love the platform.

@sjb-sjb
Copy link

sjb-sjb commented May 29, 2022

@StephenCleary how do I catch the exception at the top level in the synchronization context? Wouldn’t I have to re-write and install the synchronization context to do that?

@mattjohnsonpint
Copy link

Even when the exception is caught, it is loosing all important detail such as message and stack trace. See #7160

@quangtrang1111
Copy link

quangtrang1111 commented Jun 11, 2022

Please can anyone work on this issue?
I cannot trace the bug with this exception. Or at least, we should have a workaround to catch this exception we cannot let the app crash in the end user.

@bpulliam bpulliam added the Crash whenever user reports a crash or app freeze label Oct 13, 2022
@Scottj1s
Copy link
Member

Closing this issue, having captured remaining issues

@Scottj1s
Copy link
Member

@gabbybilka Can we see to it that the workarounds noted above are relnoted for the 1.2 release?

@Scottj1s
Copy link
Member

Scottj1s commented Nov 1, 2022

Reopening this issue to cover app event/callback handlers, which are better addressed in WinUI3 code. The only change necessary to C#/WinRT is caching the UnhandledExceptionEventArgs.Exception object.

@Scottj1s
Copy link
Member

Issue has been fixed internally and will be included in v1.3

@ghost ghost removed the needs-triage Issue needs to be triaged by the area owners label Nov 11, 2022
@gabbybilka
Copy link
Member

🎉Microsoft.WindowsAppSDK.1.2.221209.1 has been released which fixes this issue.

Handy links:

@bogdan-patraucean
Copy link

bogdan-patraucean commented Jan 5, 2023

Hello @Scottj1s , I can still reproduce it in this scenario:

This code requires elevation to open that exe, so if elevation is not configured, process.Start(); will throw an error that will not be handled.

[RelayCommand]
public async Task OpenPropertiesPerf() => await OpenProperties();

public static Task OpenProperties()
{
        return Task.Run(() => StartProcess("SystemPropertiesPerformance.exe"));
}

private static Process StartProcess(string fileName)
{
        var process = new Process
        {
            StartInfo = new ProcessStartInfo
            {
                FileName = fileName,
                Verb = "open",
                CreateNoWindow = true,
            },
        };
       
        process.Start();

        return process;
}

@ghost ghost added the needs-triage Issue needs to be triaged by the area owners label Jan 5, 2023
@gabbybilka gabbybilka added this to the WinUI 3 in WinAppSDK 1.3 milestone Feb 15, 2023
@bpulliam bpulliam removed the needs-triage Issue needs to be triaged by the area owners label Mar 13, 2023
@bpulliam bpulliam removed the fixed-internally This bug has been fixed, and the fix will be shipped in the next version of WinUI 3. label Feb 29, 2024
@Inrego
Copy link

Inrego commented Mar 7, 2024

I am still experiencing a crash in my Windows MAUI app, that I for the life of me can't get any exception details of.
In App constructor, I am hooking up these events:

    this.UnhandledException += App_UnhandledException;
    System.AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
    Microsoft.UI.Xaml.Application.Current.UnhandledException += CurrentOnUnhandledException;
    AppDomain.CurrentDomain.FirstChanceException += CurrentDomain_FirstChanceException;

The app initializes fine, but under certain circumstances, the app crashes when I navigate to a specific page.
Those circumstances cannot be reproduced on my development machine, it only happens on some laptops.

Either way, each of the above event handlers will write the exception to a txt file. But none of them fire.
I went down this path, because Sentry didn't pick up the exceptions either. It's really frustrating to work with.

I am using .NET 8 MAUI, which depend on Microsoft.WindowsAppSDK v1.3.230724000

@microsoft-github-policy-service microsoft-github-policy-service bot added the needs-triage Issue needs to be triaged by the area owners label Mar 7, 2024
@sjb-sjb
Copy link

sjb-sjb commented Mar 7, 2024

@Inrego check out #8885 linked above. If it also applies to MAUI then the fix is to wrap delegates in try / catch before dispatching them to the UI thread, and call the unhandled event handler yourself in the catch clause.

@Inrego
Copy link

Inrego commented Mar 7, 2024

After all this debugging, I have try/catch everywhere related to the crash. Nothing is caught, it still crashes.
If connected with TeamViewer to the PC, it doesn't crash. It's such a weird thing.
I'm at a place where I can remove the crash by removing some UI elements. But adding just a <Label Text="Test" /> will make the crash happen again.
On some PCs, it helps to maximize the window, on others not.
Only thing I get when it crashes, is an entry in event viewer, which doesn't give me much:

Navn på program med fejl: Iris.MAUI.exe, version: 1.0.0.0, tidsstempel: 0x65a80000
Navn på modul med fejl: Microsoft.ui.xaml.dll, version: 3.1.3.0, tidsstempel: 0xea4b25b7
Undtagelseskode: 0xc0000005
Forskydning med fejl 0x00000000009327cd
Proces-id 0x0x1A68
Programmets starttidspunkt 0x0x1DA7083B99B077A
Programsti: C:\Program Files\WindowsApps\c8389d99-ee7a-4c64-a3f0-6bd7acefbbb5_1.0.38.0_x64__970kh9ves4628\Iris.MAUI.exe
Modulsti: C:\Program Files\WindowsApps\Microsoft.WindowsAppRuntime.1.3_3000.934.1904.0_x64__8wekyb3d8bbwe\Microsoft.ui.xaml.dll
Rapport-id: e9a003c6-d115-43da-9395-aef0515ccecd
Fuldt navn på program med fejl: c8389d99-ee7a-4c64-a3f0-6bd7acefbbb5_1.0.38.0_x64__970kh9ves4628
Relativt program-id for program med fejl: App

Sorry it's in danish, but it's an end-user PC as I am not able to replicate the crash on any of my PCs.

@StephenCleary
Copy link

@Inrego If your customer is open to this, you could try running ProcDump with the -e command line parameter, and then open the dmp file in Visual Studio. You should be able to get a call stack at least.

@Inrego
Copy link

Inrego commented Mar 7, 2024

Thanks, I'll keep that in mind. I finally found a fix. A horizontal CollectionView seems to have been the culprit.
Changing it to RadListView from Telerik at least seems to have stopped the crash for now.

What boggles my mind is why it only crashed on some PC's. And why a TeamViewer connection to the PC almost always prevented the crash. And sometimes maximizing the window prevented the crash.

Anyhoo, after a few days of trying different things, it finally seems crash-free now. Our next app def. won't be in MAUI.

@k563
Copy link

k563 commented Mar 7, 2024

In the WinUI Community Call yesterday, Scott illustrated how in 1.5 it's possible to debug the underlying WinUI code and see where the exception is being thrown. He showed an example where the UnhandledException event was not being fired if the exception was related to a 'NaN', whereas an error due to an unexpected negative value did raise that event. It seems that there are still a few places like this in the WinUI code which have yet to be cleaned up. So this kind of silent crash will be possible in any WinUI app, and it's not necessarily MAUI's fault. A desktop app or an Uno app would be equally susceptible ?

@Inrego
Copy link

Inrego commented Mar 7, 2024

I'm aware it's a WinUI issue. But MAUI hasn't been great all around. So for our next app, we'll probably look at choices outside the .NET ecosystem

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area-Application area-ErrorHandling Issues related to error reporting and debugging bug Something isn't working Crash whenever user reports a crash or app freeze needs-triage Issue needs to be triaged by the area owners product-winui3 WinUI 3 issues v0.8 Issues introduced in the Project Reunion 0.8 prerelease
Projects
None yet
Development

No branches or pull requests