简体   繁体   中英

Error handling with Either in Scala

This is a followup to my previous question . Suppose I have the following functions:

type Result[A] = Either[String, A] // left is an error message

def f1(a: A): Result[B] = ...
def f2(b: B): Result[C] = ...
def f3(c: C): Result[D] = ...

def f(a: A): Result[D] = for {
  b <- f1(a).right
  c <- f2(b).right
  d <- f3(c).right
} yield d; 

Suppose also I would like to add more information to the error message.

 def f(a: A): Result[D] = for {
  b <- { val r = f1(a); r.left.map(_ + s"failed with $a"); r.right }
  c <- { val r = f2(b); r.left.map(_ + s"failed with $a and $b"); r.right }
  d <- { val r = f3(c); r.left.map(_ + s"failed with $a, $b, and $c"); r.right } 
} yield d; 

The code looks ugly. How would you suggest improve the code ?

The code looks ugly because you're repeating yourself.

Write a method instead! Or an extension method. One of these, maybe:

implicit class StringEitherCanAdd[A](private val e: Either[String, A]) extends AnyVal {
  def info(s: String): Either[String, A] = e.left.map(_ + s)
  def failed(a: Any*): Either[String, A] =
    if (a.length == 0) e
    else if (a.length == 1) e.left.map(_ + s"failed with ${a(0)}")
    else if (a.length == 2) e.left.map(_ + s"failed with ${a(0)} and ${a(1)}")
    else e.left.map(_ + s"failed with ${a.init.mkString(", ")}, and ${a.last}")
}

Now you just

f1(a).info(s"failed with $a").right
f2(b).failed(a,b).right

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM