android - 协程异常抛出 KotlinNullPointerException
问题描述
我从 Firebase 请求一个对象,但在请求它之前,我检查是否有活动的互联网连接以获得结果,我以这种方式调用我的 repo
视图模型
class ArtistsViewModel(private val repo: IArtists):ViewModel() {
val fetchArtistsList = liveData(Dispatchers.IO){
emit(Resource.Loading())
try {
val artistList = repo.getArtists()
emit(artistList)
}catch (e:Exception){
Crashlytics.logException(e.cause)
emit(Resource.Failure(e.cause!!))
}
}
}
回购
class ArtistsRepoImpl : ArtistsRepo {
override suspend fun getArtists(): Resource<MutableList<Artist>> {
val artistList = mutableListOf<Artist>()
if(InternetCheck.isInternetWorking()){
val resultList = FirebaseFirestore.getInstance()
.collection("artists")
.get().await()
}else{
throw Exception("No internet connection")
}
return Resource.Success(artistList)
}
}
现在,当没有互联网连接时,异常应该返回到我的视图模型,这是我throw Exception("No internet connection")
用来传播异常的地方,但现在在我的视图模型中我收到了这条消息
com.presentation.viewmodel.ArtistsViewModel$fetchArtistList$1.invokeSuspend(ArtistsViewModel.kt:22) 的 kotlin.KotlinNullPointerException kotlinx.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33) 的 kotlinx.coroutines.DispatchedTask.run (Dispatched.kt:241) 在 kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:594) 在 kotlinx.coroutines.scheduling.CoroutineScheduler.access$runSafely(CoroutineScheduler.kt:60) 在 kotlinx.coroutines.scheduling。 CoroutineScheduler$Worker.run(CoroutineScheduler.kt:740)
错误日志指向我的 ViewModel 中的这一行
emit(Resource.Failure(e.cause!!))
我不明白为什么KotlinNullPointerException
它应该在什么时候处理我抛出的异常消息。
另外,有没有更好的方法来捕获我的 ViewModel 上的任何异常而不是Exception ?
解决方案
KotlinNullPointerException 可能发生在您与操作员强制进行可空类型的不安全类型对话时!!
。这意味着该对象e.cause
实际上是空的。您应该检查它是否为空,而不是盲目地假设它是非空的。
您应该做的是检查异常类的类型,以查看它是否与您在缺乏网络连接的情况下预期的异常相对应。
推荐阅读
- maps - 我应该使用哪些工具来构建数据可视化仪表板
- ruby-on-rails - Rails 中的内部连接 options_from_collection_for_select
- amazon-web-services - CodeDeploy 如何使用动态端口映射?
- vb.net - Outlook VBA 忽略过滤器并删除共享日历中的所有约会
- java - 使用 Oracle JDBC,如果我不 COMMIT select-only transactions 会遇到什么问题
- haskell - 如何让 mkPersist 捕获一个类型化的列表?
- ios - 无法创建 iOS 模拟器
- html - 使下拉菜单在引导程序中浮动
- sql - 如何在SQL中找到谁是部门的老板?
- ansible - 如果至少有一个主机有变量,则对所有主机运行 Ansible 任务