【问题标题】:Global exception handling in Xamarin.FormsXamarin.Forms 中的全局异常处理
【发布时间】:2019-07-18 18:55:58
【问题描述】:

有没有办法在 Xamarin.Forms 应用中处理全局级别的异常?

目前我的应用程序有一个登录页面,其中有一个按钮“抛出异常”按钮绑定到“Exception_Clicked”方法。

private void Exception_Clicked(object sender, EventArgs e)
{
        throw new Exception("ERROR MESSAGE");
}

我想要完成的是让应用程序管理该方法引发的异常,而无需在每个方法中显式地放置一个 try-catch。

目前我知道全局异常处理可以在常规 Web 和桌面应用程序中使用如下代码进行处理

public static class ExceptionHandlerHelper
{
    public static void Register()
    {
        AppDomain.CurrentDomain.FirstChanceException += (sender, eventArgs) =>
        {
            Console.WriteLine(eventArgs.Exception.ToString());
            Logging.LogException(eventArgs.Exception, string.Empty);
        };
    }
}

有没有办法在 xamarin.forms 中做到这一点,它是如何工作的?

编辑 1 - 虽然Global Exception Handling in Xamarin Cross platform 中提供的答案非常接近,但不幸的是它并没有阻止应用程序关闭,并且只显示异常发生位置的日志。我试图实现的异常处理必须在异常发生时捕获它并允许应用程序正常继续

【问题讨论】:

标签: c# xamarin.forms


【解决方案1】:

我已经有这个疑问并寻找类似的解决方案。但是,阅读它,我发现这不是很好的异常处理实践。我发现并适应我的需求的最好的是 SafelyExecute 设计模式。

像这样:

>

public async Task<SafelyExecuteResult> SafelyExecute(Action method, string genericErrorMessage = null)
{
    try
    {
        method.Invoke();
        return new SafelyExecuteResult { Successful = true };
    }
    catch (HttpRequestException ex)
    {
        await PageDialogService.DisplayAlertAsync(AppResources.Error, AppResources.InternetConnectionRequired, AppResources.Ok);
        return new SafelyExecuteResult { Successful = false, raisedException = ex };
    }
    catch (Exception ex)
    {
        await PageDialogService.DisplayAlertAsync(AppResources.Error, genericErrorMessage ?? ex.Message, AppResources.Ok);
        return new SafelyExecuteResult { Successful = false, raisedException = ex };
    }
    //You can add more exception here
}

还有被叫:

>

await SafelyExecute(() => { /*your code here*/ });

>

public class SafelyExecuteResult
    {
        public Exception raisedException;
        public bool Successful;
    }

很遗憾,您需要在需要跟踪异常的地方使用此方法。

【讨论】:

    猜你喜欢
    • 2016-11-03
    • 2017-02-24
    • 2011-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-21
    • 2011-09-29
    • 2011-06-17
    相关资源
    最近更新 更多