코루틴에서 제일 어려운 부분 중에 하나가 예외 처리와 작업 취소 입니다. Coroutine scope이 하나만 존재하는 아주 단순한 구조라면 try catch 가 예상대로 동작을 하지만 child scope이 존재하는 경우라면 try catch가 예상대로 동작하지 않습니다. 그건 코루틴이 예외를 내부적으로 처리히서 Job hiearchy의 상위 트리로 전달하기 때문인데요. 크케 두가지 옵션이 존재합니다.
코루틴에 exception handler를 다는 방법입니다.
val handler = CoroutineExceptionHandler { _, exception ->
println("CoroutineExceptionHandler got $exception")
}
val job = GlobalScope.launch(handler) { // root coroutine, running in GlobalScope
throw AssertionError()
}
val deferred = GlobalScope.async(handler) { // also root, but async instead of launch
throw ArithmeticException() // Nothing will be printed, relying on user to call deferred.await()
}
joinAll(job, deferred)
다른 방법은 Retrofit이 Response 객체를 리턴하도록 해보세요. 이렇게 하면 아마 try -catch를 사용할 수 있을 겁니다.
코루틴을 계속 사용하실 계획이시면 코루틴 페이지에 가셔서 에러 핸들링과 작업취소에 대한 부분을 꼼꼼하게 읽어보시길 권해드립니다.
https://kotlinlang.org/docs/exception-handling.html
아래 블로그도 읽어 볼 만합니다.
https://www.techyourchance.com/kotlin-coroutines-android-reference-guide/