首页 > 解决方案 > 协程异常抛出 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 ?

标签: androidfirebasekotlinmvvmkotlin-coroutines

解决方案


KotlinNullPointerException 可能发生在您与操作员强制进行可空类型的不安全类型对话时!!。这意味着该对象e.cause实际上是空的。您应该检查它是否为空,而不是盲目地假设它是非空的。

您应该做的是检查异常类的类型,以查看它是否与您在缺乏网络连接的情况下预期的异常相对应。


推荐阅读