Vox121
Vox121

Reputation: 181

Global exception handling in Xamarin.Forms

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

Upvotes: 13

Views: 4282

Answers (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.

Upvotes: 1

Related Questions