gpt4 book ai didi

c# - Xamarin.Forms 中的全局异常处理

转载 作者:行者123 更新时间:2023-12-02 11:21:06 24 4
gpt4 key购买 nike

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

目前我的应用程序有一个登录页面,其中有一个按钮“抛出异常”按钮绑定(bind)到“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非常接近,不幸的是它不会阻止应用程序关闭,只会显示异常发生位置的日志。我试图实现的异常处理必须在异常发生时捕获它并允许应用程序正常继续

最佳答案

我已经有这个疑问并寻找类似的解决方案。但是,阅读它,我发现这不是一个好的异常处理实践。我发现并适应我需要的最好的就是 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;
}

不幸的是,您需要在需要跟踪异常的地方使用此方法。

关于c# - Xamarin.Forms 中的全局异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54865049/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com