question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Coroutine cannot catch exceptions

See original GitHub issue

When the network requests, json has an exception, kotlin coroutine cannot catch the exception, and the application crashes.

retrofit = Retrofit.Builder()
            .baseUrl(baseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .client(okHttpClient)
            .build()

NetworkInterceptor

override fun intercept(chain: Interceptor.Chain): Response {

        val request = newRequest(chain)
        val response = chain.proceed(request)
        return adapterData(response)   
 }

  private fun adapterData(response: Response): Response{
        response.body()?.let {body ->
            var json = body.string()
            //org.json.JSONException: End of input at character 0 of
            val job = JSONObject(json)
            ...
            val newBody = ResponseBody.create(body.contentType(), json)
            // new response
            return response.newBuilder().body(newBody).build()
        }
        return response
    }

fun CoroutineScope.launchTryCatch(block: suspend CoroutineScope.() -> Unit,
                                  onError: ((t: Throwable) -> Unit)?){
    launch {
        try {
            block()
        }catch (t: Throwable){
            onError?.invoke(t)
        }
    }
}

viewModelScope.launchTryCatch({
            Repository.device().groupName(group.groupId, content)
            ...
        }, ::handleException)

Coroutine uses try/catch and still can’t catch the exception. Is there anything wrong with the usage?

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:1
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

2reactions
swankjessecommented, Jul 9, 2020

This isn’t due to Retrofit coroutines; rather it’s in the contract for OkHttp Interceptors. They are only allowed to throw IOExceptions; any other exception is a crash and is delivered to the uncaught exception handler.

If you need an exception then use an IOException subclass, or wrap your exception in an IOException.

0reactions
mboukadircommented, Jul 11, 2020

Ok, thanks for your reply.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Kotlin coroutine can't handle exception - Stack Overflow
In first case, when suspend function is being called in runBlocking coroutine, exception from continuation goes to catch block, and then ...
Read more >
Coroutine exceptions handling | Kotlin
Coroutine exceptions handling. This section covers exception handling and cancellation on exceptions. We already know that a cancelled ...
Read more >
Exceptions in coroutines. Cancellation and Exceptions in…
When a coroutine fails with an exception, it will propagate said exception up to its parent! Then, the parent will 1) cancel the...
Read more >
Exception handling in Kotlin Coroutines - Kt. Academy
Catching an exception before it breaks a coroutine is helpful, but any later is too late. Communication happens via a job, so wrapping...
Read more >
Are You Handling Exceptions in Kotlin Coroutines Properly?
The second possibility is to remove the exception handler, leave the try-catch logic, but change the Repository layer to use specialised ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found