crak
crak

Reputation: 1665

Error handling in for comprehension

I have some list to browse but i whant to know if there is some touble in the browsing exemple :

val feedChildrens =  for {
   persone <- cities.getCitizens
   child <- personne.getChildrens
} yield {
   child give cake
   child
}
feedChildens match {
  case Nil => "Error no child feed"
  case _ => "Go purshace more cake !"
}

but with this system we could not have precise error like "Error this is a gost city" and "Error there is children in this city".

I know i could do somthing with match case like this

persone <- cities.getCitizens match {
  case Nil => "Error this is a gost city"
  case parents :List[Parent]   => parents.flatMap( _.getChildrens ) match {
                      case Nil => ""Error there is children in this city".
                      case  childrens :List[Children] => 
                                            childrens.map{child => 
                                                    child give cake
                                                    child 
                                             }
}

But it's look ugly and I lose the for-comprehension I try also to think about, but it's seem to use only Exception (I would like to have simple objects for my error) I and the monad try are use before the sequences monad in the for-comprehension, what is great but block me.

So I wonder if it's possible to have a clean way to report error during the for-comprehension

Upvotes: 1

Views: 846

Answers (1)

Gabriele Petronella
Gabriele Petronella

Reputation: 108169

If you want to "fail fast" and report the first error you encounter, then a Try is what you're looking for.

When you compose Try instances, you'll get a Success[T] if everything went smooth and a Failure[E] in case something failed, where the Failure is the first one occurred.

If you instead need to accumulate the errors, then a monad is not the appropriate abstraction, as monad composition is designed to cut the chain as soon as possible: you'll need something more powerful (technically speaking an applicative functor), like the Validation provided by scalaz.

Upvotes: 3

Related Questions