Xamarin.Forms中的全局异常处理

13

在Xamarin.Forms应用程序中是否有一种处理异常的全局方法?

目前我的应用程序有一个登录页面,其中有一个按钮“Throw Exception”与“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中实现此功能的方法,它如何工作? EDIT 1-虽然在Xamarin跨平台全局异常处理中提供的答案非常接近,但不幸的是它不会阻止应用程序关闭,只会显示异常发生的位置日志。我正在尝试实现的异常处理必须捕获异常并允许应用程序正常运行。

4
可能是 Xamarin 跨平台中的全局异常处理 的重复问题。 - Gerald Versluis
2
关于您的编辑; 您无法阻止应用程序崩溃,只能从中获取信息。 在此发生时,无论您做什么,应用程序都将关闭。 请参见 https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Exceptions/Concepts/UncaughtExceptions.html 和 https://developer.android.com/reference/java/lang/Thread.UncaughtExceptionHandler。 - Gerald Versluis
@GeraldVersluis 谢谢。看起来我正在尝试将我的 Web / 桌面体验强制转移到移动环境中,但并没有取得太大的成功。 - Vox121
你找到解决方法了吗?我这里也有完全相同的问题。 - GuidoG
1个回答

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接