简体   繁体   中英

Catching an exception thrown from the click handler of a ContentDialog outside of ShowAsync()

Currently if I throw an exception somewhere down the call stack from the click handler it will crash the application. Is there a way to allow the exception out of the ContentDialog.ShowAsync()?

    public async Task<bool> ShowLoginDialogAsync(LogInType loginType) {         
        var loginDialog = new LoginDialog(loginType);
        try {
            await loginDialog.ShowAsync(); <-- Exception thrown in click handler will crash the app
        }
        catch { } <-- I'd like to cach login exceptions here rather than be limited the ContentDialog return result
        return loginDialog.Result;
    }

    public sealed partial class LoginDialog {

        private async void OkClicked(ContentDialog contentDialog, ContentDialogButtonClickEventArgs args) {
            await Validate(); <-- last chance to catch an exception or crash?
        }
}

The OkClicked code doesn't run inside the loginDialog.ShowAsync() , it runs independently. You have to wrap the call to Validate in a try/catch if you want to get the exception from it, or it will just propagate to the context and, uncaught, crash the application.

I've currently decided to use the following strategy in several places to work with converting our WinForms/WPF app to UWP. I wouldn't normally do this and I may choose to factor it out later, but this code allows me to propagate exceptions out of the ContentDialog and abide the async/await pattern:

public sealed partial class LoginDialog {
    public Exception Exception { get; private set; }

    private async void OkClicked(ContentDialog contentDialog, ContentDialogButtonClickEventArgs args) {
            try {
                await Validate();
            }
            catch (Exception e) {
                Exception = e;
            }
        }
}

public async Task<bool> ShowLoginDialogAsync(LogInType loginType) {

            var loginDialog = new LoginDialog(loginType);

            await loginDialog.ShowAsync();

            switch (loginDialog.Exception) {
                case null:
                    break;
                default:
                    throw loginDialog.Exception;
            }

            return loginDialog.Result;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM