Home > Software engineering >  Throwing exception with coroutine crashes app instead of handling failure in try/catch block
Throwing exception with coroutine crashes app instead of handling failure in try/catch block

Time:02-21

view model :

val link: String? = null
if(link.isNullOrEmpty()){
    throw IllegalArgumentException(mApplication.resources.getString(R.string.server_in_maintenance_please_try_again_later))
}

fargment :

try{
    //calling the viewmodel function
}catch (e:IllegalArgumentException){
   Toast.makeText(requireContext(), e.localizedMessage, Toast.LENGTH_SHORT).show()
}catch (e:Exception){
   Toast.makeText(requireContext(), e.localizedMessage, Toast.LENGTH_SHORT).show()
}

I assigned null into the "link" to demonstrate calling from the API when the API's server is in maintenance or shut down temporarily..

this is the stack trace -

E/AndroidRuntime: FATAL EXCEPTION: DefaultDispatcher-worker-4
Process: com.amagen.supercheap, PID: 12491
java.lang.IllegalArgumentException: MY MESSAGE FROM RESOURCE FILE
    at com.amagen.supercheap.MainActivityViewModel$createSuperItemsTable$2$1.invokeSuspend(MainActivityViewModel.kt:112)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
    at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:571)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:678)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:665)

CodePudding user response:

You need to add CoroutineExceptionHandler where you a starting Coroutine and inside that exceptionHandler variable you will get the exception details. It will also prevent app from crashing.

Sample code below

private val exceptionHandler = CoroutineExceptionHandler { context, exception ->
    exception.message?.let { Log.d("Error", it) }
}


lifecycleScope.launch(kotlinx.coroutines.Dispatchers.IO   exceptionHandler) {
}

CodePudding user response:

Why don't you catch errors in coroutines this way?

private val dispatcher: CoroutineDispatcher = Dispatchers.Default
private val coroutineScope = CoroutineScope(dispatcher)
private val handler = CoroutineExceptionHandler { _, _ ->
    Logger.e("Caught : Exception ...")
}
 
coroutineScope.launch(handler) {
            
}
  • Related