Exception thrown inside Coroutine Worker shuts down the worker

32 views Asked by At

There is a task that is performed by calculateSomething() inside the doWork() method of the Coroutine Worker and a failure in the calculateSomething() method shuts down the worker. I get the following exception.

2024-03-13 14:34:38.702 19461-26830 WM-WorkerWrapper com.example.dev E Work [ id=f98fdc50-39a8-4631-a1a6-3055dd7795ca, tags={ com.example.splash.workmanager.DeviceIdWorker } ] failed because it threw an exception/error

Despite adding a try catch, the catch block is not able to catch it & print the error message. Any help in understanding this behavior will be helpful for me.

override suspend fun doWork(): Result {

 return try {

     return withContext(context = coroutineDispatcher.io) {
         
            calculateSomething()
            Result.success()
        }
    } catch (exception: Exception) {
        println("Exception" + exception.message)
        return Result.failure()
    }
}

override suspend fun calculateSomething(
    context: Context
): String {

return suspendCancellableCoroutine<String> {

    service.registerSomething(object : Callback<JSONObject> {

            override fun onSuccess(data: JSONObject?) {

                val result = data
                 it.resume(result.toString())

            }

            override fun onFailure(e: Exception?) {
                    e.printStackTrace()
                    it.resumeWithException(e?.cause ?: NullPointerException())
                }
            }
      }
}
0

There are 0 answers