【问题标题】:How to catch unhandled exceptions in the Room persistence library如何在 Room 持久性库中捕获未处理的异常
【发布时间】:2020-01-22 12:12:56
【问题描述】:

背景:

我在我的 Android (Java) 项目中使用 Room 持久性库来支持数据的本地缓存。 Room 在查询或保存数据时在专用线程上运行。

问题:

如果在 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 在后台线程中执行许多操作,我希望有一种方法可以注册自定义错误处理程序。你知道如何实现这一目标吗?如果没有,如果出现此类异常,您对如何自动擦除数据库有其他建议吗?

【问题讨论】:

  • 我建议你提供一个 minimal reproducible example 来展示你的 DAO。或者,至少:你的 DAO 方法返回什么?我的猜测是他们正在返回LiveData
  • 是的,他们正在返回 LiveData。我添加了 DAO 定义。
  • LiveData 不能引发错误。这就是我不喜欢让 DAO 使用 LiveData 的原因之一。如果您切换到 RxJava 类型(例如,SingleObservable),您应该通过正常的 RxJava 链得到错误。或者,如果有一天你迁移到 Kotlin,你的异常应该通过正常的 suspendFlow 处理暴露出来。

标签: java android android-room


【解决方案1】:

可以通过注册一个执行自定义异常处理程序的自定义线程来实现该目标。

我想出了以下解决方案:

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);
        }
    }

【讨论】:

  • 我发现“executor”从未运行?
【解决方案2】:

我不认为你可以对这些做些什么,它假设架构是正确的,但如果数据或架构有问题,那么你可以在插入或对它们进行任何操作时处理这样的事情。

只需将 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()
  }
}

【讨论】:

猜你喜欢
  • 2011-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-10
  • 2011-10-27
  • 2017-11-25
  • 1970-01-01
相关资源
最近更新 更多