9. Errors as values
Several methods in Fully Booked answer None when they can’t do what they were asked. With next and reserve, that leaves the caller guessing at the reason. A Java method in that position would probably throw an exception with a message in it. Scala code in the functional style returns the failure to its caller as an ordinary value, with a type that says what can go wrong.
9.1. Naming what can go wrong
Create errors.scala, with a type for the failures and a method that puts them into words:
package fullybooked
import java.time.LocalTime
enum BookingError:
case NotAllowed(status: Status, event: Event)
case PartyTooLarge(size: Int)
case NothingFree(size: Int, time: LocalTime)
def explain(error: BookingError): String = error match
case BookingError.NotAllowed(status, event) =>
s"$event isn't possible when the booking is ${describe(status)}"
case BookingError.PartyTooLarge(size) =>
s"we can't seat $size, our largest table takes ${Booking.largestParty}"
case BookingError.NothingFree(size, time) =>
s"no table for $size is free at $time"
The errors are cases of an enum like Status. They aren’t exceptions: they have no stack trace and nothing throws them. NotAllowed holds the status and the event that didn’t go together. PartyTooLarge holds the size that was asked for, and NothingFree the size and the time. The wording is all in explain, where the compiler will warn us if we add an error and leave it out.
9.2. Either
Replace next in events.scala with a version that says why it refused:
def next(status: Status, event: Event): Either[BookingError, Status] = (status, event) match
case (Status.Requested, Confirm) => Right(Status.Confirmed)
case (Status.Confirmed, Arrive(at)) => Right(Status.Seated(at))
case (Status.Confirmed, FailToArrive) => Right(Status.NoShow)
case (Status.Seated(_), Leave) => Right(Status.Completed)
case (Status.Requested | Status.Confirmed, Cancel(reason)) =>
Right(Status.Cancelled(reason))
case _ => Left(BookingError.NotAllowed(status, event))
The return type is now Either[BookingError, Status]. An Either is a Left or a Right. Here a Left holds a BookingError and a Right holds a Status. Nothing in the language says which side is the failure. The convention, which the standard library follows throughout, is that Right is the answer you wanted and Left is the error, with the error’s type written first.
The project won’t compile until handle and lifecycle have caught up with that. In model.scala, handle only needs its return type changed:
def handle(event: Event): Either[BookingError, Booking] =
next(status, event).map(newStatus => copy(status = newStatus))
On an Either, map changes the value inside a Right and passes a Left along untouched, so a refusal from next comes out of handle unchanged. flatMap and for skip a Left too, as they skipped None on an Option.
Replace lifecycle in main.scala with a version that matches on the two sides:
@main def lifecycle(): Unit =
var booking = Booking(Party("Moreau", 3), Table(3, 4), LocalTime.of(20, 15))
val events = List(Confirm, Arrive(LocalTime.of(20, 10)), Cancel("too noisy"), Leave)
for event <- events do
booking.handle(event) match
case Right(changed) =>
booking = changed
println(s"$event: ${describe(booking.status)}")
case Left(error) =>
println(explain(error))
$ scala run . --main-class fullybooked.lifecycle
Confirm: confirmed
Arrive(20:10): at the table since 20:10
Cancel(too noisy) isn't possible when the booking is at the table since 20:10
Leave: been and gone
The third line now comes from explain, by way of the error that next returned. The tests in events.test.scala need bringing up to date as well. Here’s the whole file:
package fullybooked
import java.time.LocalTime
class EventTests extends munit.FunSuite:
val eight = LocalTime.of(20, 0)
val requested = Booking(Party("Moreau", 3), Table(3, 4), eight)
test("a booking goes from requested to completed"):
val events = List(Confirm, Arrive(eight), Leave)
val start: Either[BookingError, Booking] = Right(requested)
val end = events.foldLeft(start): (booking, event) =>
booking.flatMap(_.handle(event))
assertEquals(end.map(_.status), Right(Status.Completed))
test("a cancelled booking can't be seated"):
val cancelled = requested.handle(Cancel("flu"))
assertEquals(cancelled.map(_.status), Right(Status.Cancelled("flu")))
assertEquals(
cancelled.flatMap(_.handle(Arrive(eight))),
Left(BookingError.NotAllowed(Status.Cancelled("flu"), Arrive(eight)))
)
test("a party at its table can't cancel"):
val seated = requested.copy(status = Status.Seated(eight))
assert(seated.handle(Cancel("changed our minds")).isLeft)
test("seated parties hold their table"):
assert(holdsTable(requested.copy(status = Status.Seated(eight))))
In the first test, start has its type written out. Left to itself the compiler would give a bare Right(requested) the type Right, and then reject the fold because handle can return a Left. Chapter 8 wrote Option(requested) to get round the same problem. The second test checks which error came back and what it holds. The third only cares that something failed, so it checks isLeft, which is true for any Left.
9.3. From an Option to an Either
In chapter 5 a party of five and a party of nine both got None from the restaurant, for different reasons. Replace reserve in availability.scala with a version that gives each its own error:
def reserve(store: BookingStore, party: Party, time: LocalTime): Either[BookingError, Booking] =
if party.size > Booking.largestParty then Left(BookingError.PartyTooLarge(party.size))
else
bestTable(party, time, store.all)
.toRight(BookingError.NothingFree(party.size, time))
.map: table =>
Thread.sleep(300)
val booking = Booking(party, table, time, Status.Confirmed)
store.add(booking)
booking
A party bigger than the largest table gets a Left straight away. For the rest, bestTable still returns an Option[Table]. toRight turns that into an Either: a Some becomes a Right, and None becomes a Left holding the error we give it. I’ve left bestTable as it was. reserve turns the over-large party away before it calls bestTable, so a None from there can now only mean that nothing is free.
In desk.scala, replace reply so that it takes the new type and gets its wording from explain:
def reply(name: String, result: Either[BookingError, Booking]): String = result match
case Right(booking) => s"$name: table ${booking.table.number} at ${booking.time}"
case Left(error) => s"$name: sorry, ${explain(error)}"
The project won’t compile again until lastTable and one test have caught up. In lastTable, replace the lines from var toIbrahim down to the two printlns that follow the joins once more:
def ask(party: Party): String = reply(party.name, reserve(store, party, eight))
var toIbrahim = ""
var toCastellanos = ""
val first = Thread(() => toIbrahim = ask(Party("Ibrahim", 7)))
val second = Thread(() => toCastellanos = ask(Party("Castellanos", 8)))
first.start()
Thread.sleep(100)
second.start()
first.join()
second.join()
println(toIbrahim)
println(toCastellanos)
The first new line defines ask inside lastTable. Scala allows a method inside a method. The inner one can use store and eight from the method around it. In store.test.scala, the test of reserve should now expect Right(Table(1, 2)) where it had Some(Table(1, 2)). Run the tests.
9.4. A request from outside
So far we’ve written every Party into the code ourselves. Real bookings arrive as text, from a web form or a command line, and text can be wrong in ways our types don’t allow inside the program: a size of “two”, a time of “8pm”. The place where outside text is turned into values of our own types is usually called the boundary. We’ll do all the checking there, once, so that everything behind it can rely on the types.
A request can fail in four more ways. Add the cases to the end of BookingError:
case NameMissing
case BadPartySize(text: String)
case BadTime(text: String)
case BadPhone(text: String)
Add their wording to the end of explain:
case BookingError.NameMissing => "we need a name for the booking"
case BookingError.BadPartySize(text) => s"'$text' isn't a number of people"
case BookingError.BadTime(text) => s"'$text' isn't a time, try 19:30"
case BookingError.BadPhone(text) => s"'$text' isn't a phone number"
Now create request.scala:
package fullybooked
import java.time.LocalTime
case class BookingRequest(name: String, size: String, time: String, phone: String)
def nameIn(request: BookingRequest): Either[BookingError, String] =
val name = request.name.trim
if name.isEmpty then Left(BookingError.NameMissing) else Right(name)
def sizeIn(request: BookingRequest): Either[BookingError, Int] =
request.size.toIntOption
.filter(_ > 0)
.toRight(BookingError.BadPartySize(request.size))
def phoneIn(request: BookingRequest): Either[BookingError, Option[Phone]] =
if request.phone.isBlank then Right(None)
else
Phone.parse(request.phone) match
case Some(phone) => Right(Some(phone))
case None => Left(BookingError.BadPhone(request.phone))
A BookingRequest is all strings, because that’s what arrives. Each of the three methods looks at one field and returns either a value of the type we really want or the reason it couldn’t produce one. In sizeIn, toIntOption gives None for “two”. filter then keeps a Some only when its number is above zero, so “0” and “-3” end up as None too. toRight turns the result into an Either. The trim and isBlank in the other two are methods on Java’s String.
The type of phoneIn has an Option inside an Either. No number at all is fine and gives Right(None). A good number gives Right(Some(phone)). Something that was typed but isn’t a number is a Left, so the customer from the end of chapter 8 can be told their number wasn’t understood.
9.5. Exceptions at the boundary
The time is harder, because the obvious way to parse it is LocalTime.parse, which throws a DateTimeParseException for “8pm”. Add import scala.util.Try under the other import in request.scala, then add this to the end of the file:
def timeIn(request: BookingRequest): Either[BookingError, LocalTime] =
Try(LocalTime.parse(request.time)).toOption
.toRight(BookingError.BadTime(request.time))
Wrapping the call in Try(...) runs it and catches whatever it throws, short of something fatal like an OutOfMemoryError. The result is a Success holding the value or a Failure holding the exception. toOption reduces that to a Some or a None, ready for toRight.
I use Try where our code calls a Java method that throws, and convert the result on the same line. Chapter 2 mentioned that Scala has try and catch, and exercise 2 has you write timeIn with them. I don’t pass a Try around, because the error inside one is always a Throwable. A caller learns no more from that than from throws Exception in Java.
I return an Either for failures that are part of the job, such as bad input, a full restaurant or a move that isn’t allowed. The caller is expected to deal with those, and the return type tells it they can happen. I don’t catch the exception from a bug or a lost database connection. Nobody near the failing line can do much about one of those, so it travels up to the top of the program.
9.6. The first problem or all of them
Add two methods to the end of request.scala. The first stops at the first check that fails, and the second runs all four:
def validateFast(request: BookingRequest): Either[BookingError, (Party, LocalTime)] =
for
name <- nameIn(request)
size <- sizeIn(request)
time <- timeIn(request)
phone <- phoneIn(request)
yield (Party(name, size, phone), time)
def validate(request: BookingRequest): Either[List[BookingError], (Party, LocalTime)] =
(nameIn(request), sizeIn(request), timeIn(request), phoneIn(request)) match
case (Right(name), Right(size), Right(time), Right(phone)) =>
Right((Party(name, size, phone), time))
case (name, size, time, phone) =>
Left(List(name, size, time, phone).flatMap(_.left.toOption))
In validateFast the for runs on Either. Each <- takes the value out of a Right. At the first Left the for stops with that Left as its result. The later checks don’t run, so the caller hears about one problem at a time.
The other method, validate, has List[BookingError] as its error type. It runs all four checks and then matches on the results together. If every one is a Right, it builds the party. If not, left.toOption gives Some of the error for each Left and None for each Right, and flatMap keeps what’s inside the Somes.
Someone filling in a form would usually rather see every mistake at once, so I collect the errors when I’m validating input. Steps that depend on each other have to fail fast: there’s no point looking for a table for a party we couldn’t parse. The match on four results is long-winded. Chapter 11 shortens it with a library called Cats.
Create request.test.scala and run the tests:
package fullybooked
import java.time.LocalTime
class RequestTests extends munit.FunSuite:
val good = BookingRequest("Silva", "2", "20:00", "07700 900199")
test("a good request becomes a party and a time"):
val expected = (Party("Silva", 2, Phone.parse("07700 900199")), LocalTime.of(20, 0))
assertEquals(validate(good), Right(expected))
test("the phone number can be left out"):
assertEquals(validate(good.copy(phone = "")).map((party, _) => party.phone), Right(None))
test("failing fast reports the first problem only"):
val bad = good.copy(size = "two", time = "8pm")
assertEquals(validateFast(bad), Left(BookingError.BadPartySize("two")))
test("validate reports every problem"):
val bad = good.copy(size = "two", time = "8pm")
val expected = List(BookingError.BadPartySize("two"), BookingError.BadTime("8pm"))
assertEquals(validate(bad), Left(expected))
9.7. Booking from the command line
Add one more @main to the end of main.scala, which takes its four arguments as text:
@main def book(name: String, size: String, time: String, phone: String): Unit =
val store = InMemoryBookingStore()
for booking <- tonight do store.add(booking)
val request = BookingRequest(name, size, time, phone)
val result = validate(request).flatMap: (party, time) =>
reserve(store, party, time).left.map(error => List(error))
result match
case Right(booking) => println(label(booking))
case Left(errors) =>
println("Sorry, we couldn't make that booking:")
for error <- errors do println(s" ${explain(error)}")
Here validate fails with a list of errors and reserve with a single one. To give the chain one error type, left.map wraps the error from reserve in a list. It’s map for the other side: it changes a Left and leaves a Right alone. Inside the lambda, time is the parsed LocalTime and hides the String parameter of the same name.
$ scala run . --main-class fullybooked.book -- Silva 2 20:00 "07700 900199"
20:00 table 1: Silva, party of 2
$ scala run . --main-class fullybooked.book -- Silva two 8pm "ask for Dev"
Sorry, we couldn't make that booking:
'two' isn't a number of people
'8pm' isn't a time, try 19:30
'ask for Dev' isn't a phone number
$ scala run . --main-class fullybooked.book -- Zielinski 9 20:00 ""
Sorry, we couldn't make that booking:
we can't seat 9, our largest table takes 8
$ scala run . --main-class fullybooked.book -- Achterberg 5 20:00 ""
Sorry, we couldn't make that booking:
no table for 5 is free at 20:00
The last two are the parties of nine and five from chapter 5.
9.8. Exercises
Solutions are in the book’s downloadable code, under ch09/exercises.
-
Add an error
KitchenClosed(time: LocalTime)and makereservereturn it for a time beforeopensor afterlastOrders, the two values from chapter 7. Test it. -
Write
timeWithCatch, a version oftimeInthat usestryandcatchand noTry. The syntax istry ... catch case error: DateTimeParseException => ..., and both halves are expressions. You’ll need to import the exception fromjava.time.format. -
Predict each result and then check it in a test, starting from
val four: Either[String, Int] = Right(4)andval no: Either[String, Int] = Left("no"):four.map(_ + 1),no.map(_ + 1),no.orElse(Right(1))andfour.toOption. -
Write
seatAll(bookings: List[Booking], at: LocalTime): Either[BookingError, List[Booking]], which sendsArrive(at)to every booking and stops at the first that refuses. AfoldLeftwill do it, with aforinside the lambda and a starting value declared as anEither[BookingError, List[Booking]].