Search code examples
androidexceptioncrashlyticstwitter-fabriccrashlytics-android

How to catch unhandled errors and pass them further


My question is how to catch unhandled errors in Android application and pass them further so it will indeed crash the application.

I'm creating SDK for Android and I still want developers to handle their errors but I also want to get informed about crashes of mine.

I know that to catch an error I could use:

        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread thread, Throwable ex) {

        }
    });

But how to pass it futher? How to crash application? If I use:

throw new RuntimeException(ex);

It won't crash application but rather cause ANR error.

The second question is how does Fabric (Crashlytics) library work? Mind that I also don't want to spoil workflow of Fabric if it's also present in the application.


Solution

  • In a low level UncaughtExceptionHandler is the mechanism to catch of all your application errors in case if instance of UncaughtExceptionHandler attached to application thread.

    How to crash application?

    Use this thread

    It won't crash application but rather cause ANR error.

    This happens because you throw Exception and you going inside uncaughtException method, where you throw exception again. So you have a cycle.

    But how to pass it futher?

    I suppose you need to save exception data to some storage - SD card, send crash info to email, etc.

    In this case you need implement your logic inside uncaughtException method.
    You don't need to pass it futher!

    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread thread, Throwable ex) {
                   // put your save logic here
                   // save to file, send to email, etc.
                   // Also you can get information about throwed exception
                   // for example : ex.getMessage();
            }
        });
    

    You need put Thread.setDefaultUncaughtExceptionHandler(...) to your Application class for the best case.

    The second question is how does Fabric (Crashlytics) library work? Mind that I also don't want to spoil workflow of Fabric if it's also present in the application.

    Fabric uses also UncaughtExceptionHandler to catch all errors in your app.

    If you need to see error in logcat

    Just filter logcat by Answers tag. Or by System.exit