7 Handling errors and exceptions

 

In this chapter

    • Holding error information with the Either type
    • Handling errors with the biased Result type
    • Accessing and manipulating Result data
    • Lifting functions to operate on Result

    In chapter 6, you learned how to deal with optional data without having to manipulate null references using the Option data type. As you saw, this data type is perfect for dealing with the absence of data when that isn’t the result of an error. But it’s not an efficient way to handle errors because, although it allows you to cleanly report the absence of data, it swallows the cause of the absence. All missing data is treated the same way, and it’s up to the caller to try to figure out what happened. Often, this is impossible.

    In this chapter, you’ll work through a variety of exercises that teach you how to handle errors and exceptions in Kotlin. One skill you’ll learn is how to represent the absence of data due to an error, which the Option type doesn’t allow. We’ll first look at the problems that need solving, and then we’ll explore the Either type and the Result type:

    • The Either type is useful for functions that can return values of two different types.
    • The Result type is useful when you need a type that represents either data or an error.

    After some discussion and exercises using the Either and Result types, you’ll look at advanced Result handling and applying effects, and you’ll also see an advanced Result composition.

    7.1 The problems with missing data

    7.2 The Either type

    7.3 The Result type

    7.4 Result patterns

    7.5 Advanced Result handling

    7.5.1 Applying predicates

    7.6 Mapping failures

    7.7 Adding factory functions

    7.8 Applying effects

    7.9 Advanced result composition

    Summary

    sitemap