简体   繁体   English

捕获从ShowAsync()外部的ContentDialog的单击处理程序引发的异常

[英]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()? 有没有办法允许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. OkClicked代码不在loginDialog.ShowAsync()内部运行,而是独立运行。 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. 如果要从异常中获取对Validate的调用,则必须将其包装在try / catch中,否则该异常将传播到上下文,并且在未捕获的情况下使应用程序崩溃。

I've currently decided to use the following strategy in several places to work with converting our WinForms/WPF app to UWP. 我目前已决定在多个地方使用以下策略来将WinForms / WPF应用程序转换为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: 我通常不会这样做,以后可以选择将其分解,但是这段代码使我可以将异常传播到ContentDialog之外,并遵循async / await模式:

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;
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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