colin aygalinc
colin aygalinc

Reputation: 477

How to catch all coroutine uncaught exception in android without changing ```scope.launch {...}```?

I'm wondering if there is a Coroutine way to catch all Uncaught exception from any scope in android ?

I try with the Thread.setDefaultUncaughtExceptionHandler and it works but i'm wondering if this can be enable in an other way.

EDIT : I want to have the global exception handling without changing the coroutine launch. (leave the scope.launch {...} as is)

Upvotes: 4

Views: 1800

Answers (1)

Tungken
Tungken

Reputation: 1985

You can using CEH (Coroutine Exception Handler) similar Thread.uncaughtExceptionHandler like this:

class ExceptionHandlerViewModel(
    private val apiHelper: ApiHelper,
    private val dbHelper: DatabaseHelper
) : ViewModel() {

    private val users = MutableLiveData<Resource<List<ApiUser>>>()

    private val exceptionHandler = CoroutineExceptionHandler { _, exception ->
        users.postValue(Resource.error("Something Went Wrong", null))
    }

    fun fetchUsers() {
        viewModelScope.launch(exceptionHandler) {
            users.postValue(Resource.loading(null))
            val usersFromApi = apiHelper.getUsers()
            users.postValue(Resource.success(usersFromApi))
        }
    }

    fun getUsers(): LiveData<Resource<List<ApiUser>>> {
        return users
    }

}

For more information : https://kotlinlang.org/docs/reference/coroutines/exception-handling.html#coroutineexceptionhandler

Upvotes: 4

Related Questions