背景:
我正在使用Android (Java)项目中的Room persistence库来支持本地数据缓存。当查询或保存数据时,房间在专用线程上操作。
问题:
如果在由Room管理的这些线程中抛出异常,则整个应用程序将崩溃。这可能发生在数据不一致的情况下,例如数据不匹配当前架构。这是个很大的问题。我宁愿自己处理这类异常,并清除本地数据库中的所有数据--这比让用户拥有一个完全损坏和不可修复的应用程序要好。
示例例外:
2020-01-22 12:45:08.252 9159-11043/com.xyz E/AndroidRuntime: FATAL EXCEPTION: arch_disk_io_1
Process: com.xyz, PID: 9159
java.lang.RuntimeException: Exception while computing database live data.
at androidx.room.RoomTrackingLiveData$1.run(RoomTrackingLiveData.java:92)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
Caused by: java.lang.RuntimeException: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "primary" (class com.xyz.model.remotedatasource.sampleApi.entities.ProfileImage), not marked as ignorable (2 known properties: "isPrimary", "url"])
at [Source: (byte[])":)
... -1, column: 402] (through reference chain: com.xyz.model.remotedatasource.sampleApi.entities.Candidate["profileImages"]->java.util.ArrayList[0]->com.xyz.model.remotedatasource.sampleApi.entities.ProfileImage["primary"])
at com.xyz.model.localdatasource.Converters.deserialize(Converters.java:113)
at com.xyz.model.localdatasource.Converters.toCandidate(Converters.java:73)
at com.xyz.model.localdatasource.LocalDao_Impl$4.call(LocalDao_Impl.java:270)
at com.xyz.model.localdatasource.LocalDao_Impl$4.call(LocalDao_Impl.java:217)
at androidx.room.RoomTrackingLiveData$1.run(RoomTrackingLiveData.java:90)
... 3 more
示例数据访问对象(DAO):
public interface LocalDao {
@Query("SELECT * FROM Match")
LiveData<List<Match>> getMatches();
@Insert(onConflict = REPLACE)
void saveMatches(List<Match> matches);
}
问题
由于Room在后台线程中执行许多操作,所以我希望有一种方法来注册自定义错误处理程序。你知道如何做到这一点吗?如果没有,在发生此类异常时,您对如何自动删除数据库有其他建议吗?
发布于 2020-11-11 08:14:39
可以通过注册具有自定义异常处理程序的执行的自定义线程来实现此目标。
我想出了以下解决方案:
public abstract class LocalDatabase extends RoomDatabase {
private static final String TAG = LocalDatabase.class.getSimpleName();
private static final Object syncObj = new Object();
private static LocalDatabase localDatabase;
private static ConcurrentHashMap<Integer, String> dbToInstanceId = new ConcurrentHashMap<>();
private static ConcurrentHashMap<Long, String> threadToInstanceId = new ConcurrentHashMap<>();
public abstract LocalDao getDao();
public static LocalDatabase getInstance() {
if (localDatabase == null) {
localDatabase = buildDb();
}
return localDatabase;
}
private static LocalDatabase buildDb() {
// keep track of which thread belongs to which local database
final String instanceId = UUID.randomUUID().toString();
// custom thread with an exception handler strategy
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool(runnable -> {
ThreadFactory defaultThreadFactory = Executors.defaultThreadFactory();
Thread thread = defaultThreadFactory.newThread(runnable);
thread.setUncaughtExceptionHandler(resetDatabaseOnUnhandledException);
threadToInstanceId.put(thread.getId(), instanceId);
return thread;
});
LocalDatabase localDatabase = Room.databaseBuilder(App.getInstance().getApplicationContext(),
LocalDatabase.class, "LocalDatabase")
.fallbackToDestructiveMigration()
.setQueryExecutor(executor)
.build();
dbToInstanceId.put(localDatabase.hashCode(), instanceId);
return localDatabase;
}
static Thread.UncaughtExceptionHandler resetDatabaseOnUnhandledException = new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable throwable) {
Log.e("", "uncaught exception in a LocalDatabase thread, resetting the database", throwable);
synchronized (syncObj) {
// there is no active local database to clean up
if (localDatabase == null) return;
String instanceIdOfThread = threadToInstanceId.get(thread.getId());
String instanceIdOfActiveLocalDb = dbToInstanceId.get(localDatabase.hashCode());
if(instanceIdOfThread == null || !instanceIdOfThread.equals(instanceIdOfActiveLocalDb)) {
// the active local database instance is not the one that caused this thread to fail, so leave it as is
return;
}
localDatabase.tryResetDatabase();
}
}
};
public void tryResetDatabase() {
try {
String dbName = this.getOpenHelper().getDatabaseName();
// try closing existing connections
try {
if(this.getOpenHelper().getWritableDatabase().isOpen()) {
this.getOpenHelper().getWritableDatabase().close();
}
if(this.getOpenHelper().getReadableDatabase().isOpen()) {
this.getOpenHelper().getReadableDatabase().close();
}
if (this.isOpen()) {
this.close();
}
if(this == localDatabase) localDatabase = null;
} catch (Exception ex) {
Log.e(TAG, "Could not close LocalDatabase", ex);
}
// try deleting database file
File f = App.getContext().getDatabasePath(dbName);
if (f.exists()) {
boolean deleteSucceeded = SQLiteDatabase.deleteDatabase(f);
if (!deleteSucceeded) {
Log.e(TAG, "Could not delete LocalDatabase");
}
}
LocalDatabase tmp = buildDb();
tmp.query("SELECT * from Match", null);
tmp.close();
this.getOpenHelper().getReadableDatabase();
this.getOpenHelper().getWritableDatabase();
this.query("SELECT * from Match", null);
} catch (Exception ex) {
Log.e("", "Could not reset LocalDatabase", ex);
}
}
发布于 2020-01-22 17:35:24
我不认为您可以对这些操作做些什么,它假设模式是正确的,但是如果数据或模式有问题,那么您可以在插入或对它们执行任何操作时处理这样的事情。
只需将DAO函数标记为可抛出的方法,并在调用方处理可能出现的错误。
public interface LocalDao {
@Query("SELECT * FROM Match")
LiveData<List<Match>> getMatches() throws Exception;
@Insert(onConflict = REPLACE)
void saveMatches(List<Match> matches) throws Exception;
@Query("DELETE FROM Match")
public void nukeTable();
}
现在,在调用方,只需调用这个处理异常。
public getMatches(){
//... some code
try{
//some code goes here
dao.getMatches();
}catch(Exception exp){
//if something happens bad then nuke the table on background thread
dao.nukeTable()
}
}
https://stackoverflow.com/questions/59859531
复制相似问题