如何捕获Xamarin.Android中try catch块中的所有异常

时间:2018-01-29 10:43:44

标签: c# android xamarin.android

如何捕获Xamarin.Android中的try catch块中的所有异常

我对Xamarin.Android如何处理未处理的异常非常感到沮丧,这非常奇怪,我分别为所有api查询添加了三个例外:

uniqueIdentifier

这个try catch块大部分时间都可以工作,但是当我们的服务器关闭时会出现一种情况,它会抛出异常并一遍又一遍地崩溃应用程序,直到服务器重新启动。

这是一直存在的例外情况:

try
{
   // api query using `refit`
   // json parsing using `newtonsoft`
}
catch(System.OperationCanceledException e)
{
  // user cancelled the query, show option to retry
}
catch(ApiException apiException)
{
  // theres an api exception , show error message to users , show option to retry
}
catch(Exception e)
{
  // unknown exception ignore , show error message to users , show option to retry

}

正如您在JsonReaderException层次结构中所看到的,它继承了Xamarin caused by: android.runtime.JavaProxyThrowable: Newtonsoft.Json.JsonReaderException ,这是我使用的最后一个catch块。

我检查了这个System.Exception它从JsonReaderException扩展而来,我们的try catch块应该处理它。

现在我想知道是否有任何方法可以捕捉所有那些讨厌的未处理异常?

1 个答案:

答案 0 :(得分:2)

我以这种方式得到未处理的例外

    public void Init()
    {
        AndroidEnvironment.UnhandledExceptionRaiser += OnAndroidEnvironmentUnhandledExceptionRaiser;
        AppDomain.CurrentDomain.UnhandledException += OnCurrentDomainUnhandledException;
        TaskScheduler.UnobservedTaskException += OnTaskSchedulerUnobservedTaskException;

        var currentHandler = Java.Lang.Thread.DefaultUncaughtExceptionHandler;
        var exceptionHandler = currentHandler as UncaughtExceptionHandler;
        if (exceptionHandler != null)
        {
            exceptionHandler.SetHandler(HandleUncaughtException);
        }
        else
        {
            Java.Lang.Thread.DefaultUncaughtExceptionHandler = new UncaughtExceptionHandler(currentHandler, HandleUncaughtException);
        }
    }

    private void OnAndroidEnvironmentUnhandledExceptionRaiser(object sender, RaiseThrowableEventArgs e)
    {
        AndroidEnvironment.UnhandledExceptionRaiser -= OnAndroidEnvironmentUnhandledExceptionRaiser;

        _logger.LogFatal($"AndroidEnvironment.UnhandledExceptionRaiser.", e.Exception);
        e.Handled = true;
    }

    private void OnCurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        AppDomain.CurrentDomain.UnhandledException -= OnCurrentDomainUnhandledException;

        var ex = e.ExceptionObject as Exception;
        if (ex != null)
        {
            _logger.LogFatal("AppDomain.CurrentDomain.UnhandledException.", ex);
        }
        else
        {
            _logger.LogFatal($"AppDomain.CurrentDomain.UnhandledException. ---> {e.ExceptionObject}");
        }
    }

    private void OnTaskSchedulerUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
    {
        _logger.LogFatal("TaskScheduler.UnobservedTaskException.", e.Exception);
    }

    private bool HandleUncaughtException(Java.Lang.Throwable ex)
    {
        _logger.LogFatal("Thread.DefaultUncaughtExceptionHandler.", ex);
        return true;
    }