TExcelTAD
Home › Scala › Scala Error Handling Strategies

Scala Error Handling Strategies

You have now met every error-handling tool Scala offers: exceptions, Option, Either and Try. This chapter puts them side by side, shows how to convert between them, and gives practical guidelines for designing error handling in a real program.

The toolbox

Tool Represents Carries a reason? Use for
Option[A] value or nothing no lookups, optional fields, "not found"
Either[E, A] error or value yes, typed (E) expected business errors, validation
Try[A] exception or value yes, a Throwable wrapping code that throws
exceptions abnormal control flow yes bugs, broken invariants, fatal problems

Converting between them

Real programs mix sources: a map lookup gives an Option, a Java call throws, your validation returns an Either. Convert everything to one type at the boundary.

scala · try it yourself
import scala.util.Try

@main def run(): Unit =
  val opt: Option[Int] = Some(5)
  val missing: Option[Int] = None
  val tried: Try[Int] = Try("x".toInt)

  println(opt.toRight("missing value"))
  println(missing.toRight("missing value"))
  println(tried.toEither.left.map(_.getClass.getSimpleName))
  println(tried.toOption)
  println(Right(3).toOption)
  println(Left(RuntimeException("boom")).toTry.isFailure)
  println(Either.cond(10 > 5, "ok", "too small"))
Right(5)
Left(missing value)
Left(NumberFormatException)
None
Some(3)
true
Right(ok)

Strategy 1: typed domain errors

Model the errors your domain expects as an enum, and return Either. The signature then documents every way a function can fail.

scala · try it yourself
enum OrderError:
  case UnknownProduct(sku: String)
  case OutOfStock(sku: String, available: Int)
  case InvalidQuantity(q: Int)

import OrderError.*

val stock = Map("A1" -> 5, "B2" -> 0)

def reserve(sku: String, qty: Int): Either[OrderError, String] =
  for
    _         <- Either.cond(qty > 0, (), InvalidQuantity(qty))
    available <- stock.get(sku).toRight(UnknownProduct(sku))
    _         <- Either.cond(available >= qty, (), OutOfStock(sku, available))
  yield s"reserved $qty x $sku"

def message(e: OrderError): String = e match
  case UnknownProduct(s)  => s"We don't sell $s"
  case OutOfStock(s, a)   => s"Only $a of $s left"
  case InvalidQuantity(q) => s"Quantity $q is not valid"

@main def run(): Unit =
  val requests = List(("A1", 2), ("Z9", 1), ("B2", 1), ("A1", 0))
  for (sku, q) <- requests do
    println(reserve(sku, q).fold(message, identity))
reserved 2 x A1
We don't sell Z9
Only 0 of B2 left
Quantity 0 is not valid

Strategy 2: catch at the edges

Third-party and Java code throws. Wrap those calls with Try (or try/catch) as close to the call as possible, then convert to your own error type so exceptions don't leak through your whole program.

scala · try it yourself
import scala.util.Try

enum ConfigError:
  case Missing(key: String)
  case NotANumber(key: String, raw: String)

def readPort(settings: Map[String, String]): Either[ConfigError, Int] =
  for
    raw  <- settings.get("port").toRight(ConfigError.Missing("port"))
    port <- Try(raw.toInt).toEither.left.map(_ => ConfigError.NotANumber("port", raw))
  yield port

@main def run(): Unit =
  println(readPort(Map("port" -> "8080")))
  println(readPort(Map()))
  println(readPort(Map("port" -> "eighty")))
Right(8080)
Left(Missing(port))
Left(NotANumber(port,eighty))

Strategy 3: accumulate errors for validation

When validating a form, users want to see all problems at once, not just the first. Run every check, then combine:

scala · try it yourself
case class Form(name: String, age: String, email: String)
case class Person(name: String, age: Int, email: String)

def validate(f: Form): Either[List[String], Person] =
  val name  = Either.cond(f.name.trim.nonEmpty, f.name.trim, "name is required")
  val age   = f.age.toIntOption.filter(a => a > 0 && a < 150).toRight("age must be 1-149")
  val email = Either.cond(f.email.contains("@"), f.email, "email needs an @")
  (name, age, email) match
    case (Right(n), Right(a), Right(e)) => Right(Person(n, a, e))
    case _ => Left(List(name, age, email).collect { case Left(err) => err })

@main def run(): Unit =
  println(validate(Form("Ola", "29", "ola@mail.no")))
  println(validate(Form(" ", "abc", "ola.mail.no")))
Right(Person(Ola,29,ola@mail.no))
Left(List(name is required, age must be 1-149, email needs an @))

Libraries such as Cats provide a Validated type that does this combination generically.

Strategy 4: let bugs crash

Not every error should be handled. If a function receives input that "can't happen" — a negative array size, a broken invariant — throwing (or require/assert) is the honest response. Catching such errors and continuing usually hides bugs.

scala
def average(xs: Seq[Double]): Double =
  require(xs.nonEmpty, "average of an empty sequence")  // a caller bug, not a business case
  xs.sum / xs.size

Guidelines

  1. Make failure visible in types. If a function can fail in an expected way, return Option or Either, not a value plus a hidden exception.
  2. Pick one error type per layer (e.g. Either[OrderError, _] in the domain) and convert at the boundaries.
  3. Don't use null. Wrap Java results with Option(...).
  4. Never swallow exceptions with an empty catch case _ =>. At the very least, log them.
  5. Use Try only briefly — convert to Either with a meaningful error type soon after.

Tip: A good error message says what was expected, what was received and, ideally, how to fix it: "age must be 1-149, got 'abc'".

Test yourself

Which type best represents a business error like "product out of stock"?

  1. null
  2. Either[OrderError, A]
  3. Try[A]
  4. Unit

What does Either.cond(false, "ok", "bad") return?

  1. Right(ok)
  2. Left(bad)
  3. false
  4. It throws

Why does a for comprehension over Either not collect all validation errors?

  1. It does collect all errors
  2. It stops at the first Left
  3. It ignores Left values
  4. It converts errors to exceptions