Skip to content

Instantly share code, notes, and snippets.

@githubmor
Created April 13, 2019 10:34
Show Gist options
  • Save githubmor/8fcee1940bcf7b17f2a5f210b5c8c1da to your computer and use it in GitHub Desktop.
Save githubmor/8fcee1940bcf7b17f2a5f210b5c8c1da to your computer and use it in GitHub Desktop.
public class LoggingExceptionHandler implements Thread.UncaughtExceptionHandler {
private final static String TAG = LoggingExceptionHandler.class.getSimpleName();
private final static String ERROR_FILE = MyAuthException.class.getSimpleName() + ".error";
private final Context context;
private final Thread.UncaughtExceptionHandler rootHandler;
public LoggingExceptionHandler(Context context) {
this.context = context;
// we should store the current exception handler -- to invoke it for all not handled
exceptions ...
rootHandler = Thread.getDefaultUncaughtExceptionHandler();
// we replace the exception handler now with us -- we will properly dispatch the
exceptions ...
Thread.setDefaultUncaughtExceptionHandler(this);
}
@Override
public void uncaughtException(final Thread thread, final Throwable ex) {
try {
Log.d(TAG, "called for " + ex.getClass());
// assume we would write each error in one file ...
File f = new File(context.getFilesDir(), ERROR_FILE);
// log this exception ...
FileUtils.writeStringToFile(f, ex.getClass().getSimpleName() + " " + System.currentTimeMillis() + "\n", true);
} catch (Exception e) {
Log.e(TAG, "Exception Logger failed!", e);
}
}
public static final List<String> readExceptions(Context context) {
List<String> exceptions = new ArrayList<>();
File f = new File(context.getFilesDir(), ERROR_FILE);
if (f.exists()) {
try {
exceptions = FileUtils.readLines(f);
} catch (IOException e) {
Log.e(TAG, "readExceptions failed!", e);
}
}
return exceptions;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment