Adding logging if return value is None
-
26-10-2019 - |
문제
Suppose there are two functions findUser(id:String):Option[User]
and findAddress(user:User):Option[Address]
invoked as follows:
for(user <- findUser(id); address <- findAddress(user)) println(address)
Now I would like to add error logging to this for-comprehension
. I would like to call a log(msg:String)
function if either user
or address
is not found.
for(user <- findUser(id) ifNone log("user not found"); address <- findAddress(user) ifNone log("address not found")) println(address)
Can I do it without changing the function signatures?
해결책
Maybe
implicit def withIfNone[A](o: Option[A]) = new {
def ifNone(action: => Unit) = { if (o == None) action; o }
}
You may also consider using Either instead of option (or converting your options to Either). That would not work with a foreach (a for without a yield), but you might do
for(
a <- option1.toRight("option1 missing").right;
b <- option2.toRight("option2 missing").right)
yield f(a,b)
Then you can pattern match on the result with
case Left(error) => log (error)
case Right(result) => // use result
다른 팁
Lift's Box
is a more appropriate class for your usage case. A Box
is like an Option
, but with two empty states: ok and error. You could use it like this:
val addr = for {
user <- findUser(id) ?~ "user not found"
address <- findAddress(user) ?~ "address not found"
} yield address
address match {
case Full(addr) => println(addr)
case oops: Failure => println(oops.msg) // see Failure for more details
}
See this blog for various suggestions related to your problem.
It might be an overkill, but it looks pretty much like what you wanted ;)
object Extensions {
// You need a wrapper since Option is sealed
class OptionWrapper[E](option: Option[E]) {
def foreach[U](f: E => U) {
option foreach f
}
def isEmpty = option.isEmpty
}
// Modification trait for OptionWrapper
trait ErrorLogging[E] extends OptionWrapper[E] {
abstract override def foreach[U](f: E => U) {
if (isEmpty)
println("error")
else
super.foreach(f)
}
}
// Accessor for the new mixin
def log[E](option: Option[E]) = new OptionWrapper(option) with ErrorLogging[E]
}
object TestingLogger extends App {
case class User(address: String)
def findUser(id: Int): Option[User] = if (id == 1) Some(User("address")) else None
def findAddress(user: User): Option[String] = Some(user.address)
import Extensions._
for {
user <- log(findUser(1)) // prints out address
address <- log(findAddress(user))
} println(address)
for {
user <- log(findUser(2)) // prints out error
address <- log(findAddress(user))
} println(address)
}
If you have no idea of what just happened read this.