Error handling
Back in Chapter 2, A Look at Reactive Extensions, we learned how Reactive Extensions treats errors and exceptions. It provides a rich set of combinators to deal with exceptional cases and are straightforward to use.
Despite being a pleasure to work with, core.async
doesn't ship with much support for exception handling. In fact, if we write our code with only the happy path in mind we don't even know an error occurred!
Let's have a look at an example:
(defn get-data [] (throw (Exception. "Bad things happen!"))) (defn process [] (let [result (chan)] ;; do some processing... (go (>! result (get-data))) result))
In the preceding snippet, we introduced two functions:
get-data
simulates a function that fetches data from the network or an in-memory cache. In this case it simply throws an exception.process
is a function that depends onget-data
to do something interesting and puts the result into a channel, which is returned at the end.
Let's watch what happens when...