1

我的PagingSource加载一些数据。文档建议像这样捕获异常,以便将来处理LoadResult.Error

 override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Item> {
            return try {
                ...
                throw SomeCatchableException()
                ...
            } catch (e: SomeCatchableException) {
                LoadResult.Error(e)
            } catch (e: AnotherCatchableException) {
                LoadResult.Error(e)
            }
        }

但是当我尝试以这种方式处理它时:

(adapter as PagingDataAdapter).loadStateFlow.collectLatest { loadState ->

                when (loadState.refresh) {
                    is LoadState.Loading -> {
                        // *do something in UI*
                    }
                    is LoadState.Error -> {
                        // *here i wanna do something different actions, whichever exception type*
                    }
                }
            }

我想知道哪个 Exteption 会被捕获,因为我在参数LoadResult.Error(e)中传递了它(Throwable ) 。

我如何知道 loadState 处理中异常的类型?

4

1 回答 1

2

您可以在 LoadState.Error 案例中从 loadState.refresh 捕获错误,您只是错过了将 loadState.refresh 转换为 LoadState.Error。或者试试这种方式:

when (val currentState = loadState.refresh) {
   is LoadState.Loading -> {
      ...
   }
   is LoadState.Error -> {
       val extractedException = currentState.error // SomeCatchableException
       ...
   }
}
于 2021-06-10T09:07:58.003 回答