如果发生任何异常,Xamarin表单应用程序将在发布模式下崩溃

e4yzc0pl  于 2022-12-07  发布在  其他
关注(0)|答案(1)|浏览(178)

我的Xamarin Forms应用程序在任何异常发生时都会冻结。我也创建了一个异常处理程序来处理异常,但每当我遇到来自API端的异常时,它就会自动崩溃应用程序。这种情况只发生在Android中,而不会发生在iOS中。
下面是异常处理程序的代码-

public async Task<bool> HandleExceptionAsync(Exception exception)
        {
            if (exception.GetType().Name == nameof(UnauthorizedException) ||
                exception.Message.ToLowerInvariant().Contains("refresh token has expired") ||
                exception.Message.ToLowerInvariant().Contains("invalid refresh token"))
            {
                //await loginFacade.LogoutAsync(System.Threading.CancellationToken.None);
            }
            else if (exception.GetType().Name == nameof(NoInternetConnectionException))
            {
                HandleNoInternetException();
            }
            else if (CheckIfLoggable(exception))
            {
                Log.Error(exception, string.Format(Common.Constants.LoggingFormats.ExceptionWithUserDetails, _userContext.Serialize(), exception));
            }
            else
            {
#if !DEBUG
                try
                {
                    //await emailManager.SendFeedbackEmail(exception);
                }
                catch (Exception ex)
                {
                }
#endif
            }

            return true;
        }

        private bool CheckIfLoggable(Exception exception)
        {
            return exception.Message.ToLowerInvariant().Contains("not found".ToLowerInvariant()) ||
                exception.Message.ToLowerInvariant().Contains("BadInternetConnectionException".ToLowerInvariant()) ||
                exception.GetType() == typeof(NullReferenceException) ||
                exception.GetType() == typeof(OperationCanceledException);
        }

        private void HandleNoInternetException()
        {
            if (Xamarin.Essentials.Connectivity.NetworkAccess != Xamarin.Essentials.NetworkAccess.Internet)
            {
            }
            Xamarin.Essentials.Connectivity.ConnectivityChanged += Connectivity_ConnectivityChanged;
        }

        private void Connectivity_ConnectivityChanged(object sender, Xamarin.Essentials.ConnectivityChangedEventArgs e)
        {
            if (Xamarin.Essentials.Connectivity.NetworkAccess != Xamarin.Essentials.NetworkAccess.Internet)
            {
            }
            else
            {
            }
        }

我试过记录它,然后删除了导致异常的错误代码。

okxuctiv

okxuctiv1#

It is not possible to recover from exceptions that happen during UI drawing or events, using a global exception handler.

  • Use try-catch in every UI class, both in constructor, and in all event handlers (e.g. a button handler).

IMHO it’s a major PITA of Xamarin. But that is the way it is.
Even then, low level exceptions inside Xamarin code or graphics code can crash app.

  • Isolate the problem manually. Print statements, breakpoints, commenting out different code. All are sometimes necessary debugging.

相关问题