18 Error handling and testing

 

This chapter covers

  • Controlling the behavior of your code in the face of errors and exceptions
  • How error handling relates to the concept of structured concurrency
  • Writing code that behaves correctly when parts of your system fail
  • Writing unit tests for concurrent Kotlin code
  • Using the specialty test dispatcher to speed up test execution and testing fine-grained concurrency constraints
  • Testing flows with the Turbine library

Over the last few chapters, you’ve gotten an overview of the different aspects involved when writing concurrent code with Kotlin coroutines. To ensure the robustness of your applications, there is one more aspect that needs to be covered: How does your code behave when things go wrong?

Working with concurrent applications is an inherently complex task—likely, you’ll have many moving parts in your system that interact with each other. Beyond that, your application likely also interacts with other systems outside of your control. These systems may fail, or your connection to these services may be unreliable. However, even in these situations, your application should work well. One of the key aspects that enables this is proper error handling—implementing appropriate mechanisms to handle problems gracefully.

18.1 Handling errors thrown inside coroutines

18.2 Error propagation in Kotlin coroutines

18.2.1 Coroutines cancel all their children when one child fails

18.2.2 Structured concurrency only affects exceptions thrown across coroutine boundaries

18.2.3 Supervisors prevent parents and siblings from being cancelled

18.3 CoroutineExceptionHandler: The last resort for processing exceptions

18.3.1 Differences when using CoroutineExceptionHandler with launch or async

18.4 Handling errors in flows

18.4.1 Processing upstream exceptions with the catch operator

18.4.2 Retry the collection of a flow if predicate is true: The retry operator

18.5 Testing coroutines and flows

18.5.1 Making tests using coroutines fast: Virtual time and the test dispatcher