13

Is there a way to handle exceptions at a global level in a Xamarin.Forms app?

Currently my app has a login page which has a button "Throw Exception" button bound to the "Exception_Clicked" method.

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

What I am trying to accomplish is for the app to manage the exception that the method throws without explicitly putting a try-catch in each method.

Currently I know that global exception handling can be handled in regular web and desktop apps with code like below

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

Is there a way to do this in the xamarin.forms, How it would work?

EDIT 1 - while the answer presented in Global Exception Handling in Xamarin Cross platform is very close it unfortunately does not stop the application from closing and only presents a log of where the exception happened. The exception handling that I am trying to implement must catch the exception as it happens and allow the app to continue normally

Vox121
  • 181
  • 2
  • 9
  • 4
    Possible duplicate of [Global Exception Handling in Xamarin Cross platform](https://stackoverflow.com/questions/39503390/global-exception-handling-in-xamarin-cross-platform) – Gerald Versluis Feb 25 '19 at 12:03
  • 2
    In regard to your edit; you can't stop the app from crashing, you can only get the information out of it. At the point that this happens, the app will shutdown no matter what you do. See https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Exceptions/Concepts/UncaughtExceptions.html and https://developer.android.com/reference/java/lang/Thread.UncaughtExceptionHandler – Gerald Versluis Feb 25 '19 at 14:37
  • @GeraldVersluis thanks. Seems like I'm trying to force my web/desktop experience into the mobile environment without much success. – Vox121 Feb 26 '19 at 11:55
  • Did you ever found a solution ? Having the exact same question here – GuidoG Dec 14 '22 at 07:53

1 Answers1

1

I already had this doubt and looked for a similar solution. But, reading about it, I found that it is not good exception handling practice. The best I found and adapted to my needs is the SafelyExecute design pattern.

Like this:

>

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
}

And the called:

>

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

>

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

Unfortunately you will need to use this method where you need to track exceptions.