首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在Room持久性库中捕获未处理的异常

如何在Room持久性库中捕获未处理的异常
EN

Stack Overflow用户
提问于 2020-01-22 12:12:56
回答 2查看 5.6K关注 0票数 5

背景:

我正在使用Android (Java)项目中的Room persistence库来支持本地数据缓存。当查询或保存数据时,房间在专用线程上操作。

问题:

如果在由Room管理的这些线程中抛出异常,则整个应用程序将崩溃。这可能发生在数据不一致的情况下,例如数据不匹配当前架构。这是个很大的问题。我宁愿自己处理这类异常,并清除本地数据库中的所有数据--这比让用户拥有一个完全损坏和不可修复的应用程序要好。

示例例外:

代码语言:javascript
运行
复制
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):

代码语言:javascript
运行
复制
public interface LocalDao {
    @Query("SELECT * FROM Match")
    LiveData<List<Match>> getMatches();

    @Insert(onConflict = REPLACE)
    void saveMatches(List<Match> matches);
}

问题

由于Room在后台线程中执行许多操作,所以我希望有一种方法来注册自定义错误处理程序。你知道如何做到这一点吗?如果没有,在发生此类异常时,您对如何自动删除数据库有其他建议吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-11-11 08:14:39

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

我想出了以下解决方案:

代码语言:javascript
运行
复制
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);
        }
    }
票数 1
EN

Stack Overflow用户

发布于 2020-01-22 17:35:24

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

只需将DAO函数标记为可抛出的方法,并在调用方处理可能出现的错误。

代码语言:javascript
运行
复制
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();
}

现在,在调用方,只需调用这个处理异常。

代码语言:javascript
运行
复制
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()
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59859531

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档