0

I've started to work in a company which has a system with a lot of legacy code. Sometimes we have problems like the application randomly exiting, uncaught exceptions and so on. The compilation works fine and it's hard to know where exactly the error is coming from (either from legacy code or new code), so I'd like to capture exceptions globally in the application and either send them to our servers (best option) or write them to a local file in the device.

Is it possible in Xamarin.Android to write such an interface or method that catches any exception that ever occur in the application and log it to a file? If so, how?

Washington A. Ramos
  • 874
  • 1
  • 8
  • 25
  • This is the same question in native Android https://stackoverflow.com/questions/19897628/need-to-handle-uncaught-exception-and-send-log-file you can easily convert this to Xamarin.Android – MatPag Jun 22 '17 at 12:17
  • https://learn.microsoft.com/en-us/mobile-center/crashes/ – SushiHangover Jun 22 '17 at 12:35

1 Answers1

0

Yes, you can able to handle error globally, by adding some line code in ApplicationStart class, something like below:

[Application(Label = "@string/app_name", Icon = "@drawable/ic_launcher")]
public class ApplicationStart : Application
{      
    public ApplicationStart(IntPtr handle,
        global::Android.Runtime.JniHandleOwnership transfer)
        : base(handle, transfer)
    {

    }

    public override void OnCreate()
    {

        AndroidEnvironment.UnhandledExceptionRaiser += AndroidEnvironmentOnUnhandledExceptionRaiser;
        AppDomain currentDomain = AppDomain.CurrentDomain;
        currentDomain.UnhandledException += CurrentDomainOnUnhandledException;
        base.OnCreate();
    }


    private void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs e)
    {    
        //you can able to write a code here to write Exeption e to file
        Toast.MakeText(ApplicationContext, "Application crashed", ToastLength.Short).Show();   
    }

    private void AndroidEnvironmentOnUnhandledExceptionRaiser(object sender, RaiseThrowableEventArgs e)
    {
        //if you have set e.Handled = true here then when application crashed at any point at that time device not stoped your app to go more
        e.Handled = true;
        //you can able to write a code here to write Exeption e to file
        Toast.MakeText(ApplicationContext, "Application crashed", ToastLength.Short).Show();
    }
}
  • Pardon my ignorance, but do I need to implement this class or is it somewhere already in the application? I didn't find it. Again, I'm using Xamarin.Android. – Washington A. Ramos Jun 22 '17 at 14:36
  • in xamarin.android, there is not available this class by default, but you need to create new class with **Application attribute**. and implement these method in that. if any class available with **Application attribute** then you can go with same. – Pratik Patel Jun 23 '17 at 05:00