Chapter 11. Asynchronous error handling with Result

 

This chapter covers

  • Learning about the problems with Cocoa style error handling
  • Getting an introduction to Swift’s Result type
  • Seeing how Result provides compile-time safety
  • Preventing bugs involving forgotten callbacks
  • Transforming data robustly with map, mapError, flatMap, and flatMapError
  • Focusing on the happy path when handling errors
  • Mixing throwing functions with Result
  • Learning how to use errors dynamically with Result
  • How to show intent with the Never type

You’ve covered a lot of Swift’s error handling mechanics, and you may have noticed in chapter 6 that you were throwing errors synchronously. This chapter focuses on handling errors from asynchronous processes, which is, unfortunately, an entirely different idiom in Swift.

Asynchronous actions could be some code running in the background while a current method is running. For instance, you could perform an asynchronous API call to fetch JSON data from a server. When the call finishes, it triggers a callback giving you the data or an error.

11.1. Why use the Result type?

11.2. Propagating Result

11.3. Transforming values inside Result

11.4. Handling multiple errors with Result

11.5. Error recovery with Result

11.6. Impossible failure and Result

11.7. Closing thoughts

Summary

Answers