Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala's Try elegant on error behavior

Is there a more elegant way of doing this in scala?

def doTheDangerousThing(): Try[Result] = {
  val result = Try(dangerousOp)

  if (result.isFailure) {
     println("error")
  }

  result
}
like image 369
Pablo Fernandez Avatar asked Feb 04 '14 15:02

Pablo Fernandez


3 Answers

I think your if statement is perfectly valid. Here is another alternative:

def doTheDangerousThing(): Try[Result] = Try(dangerousOp) recoverWith {
    case exception => println("error"); Failure(exception)
}
like image 190
vptheron Avatar answered Nov 29 '22 08:11

vptheron


Something like this:

   def doTheDangerousThing[Result](dangerousOp: =>Result): Try[Result] = Try(dangerousOp) match {
    case o @ Failure(_) =>  println("error"); o
    case _ => _
  }
like image 20
Sane Avatar answered Nov 29 '22 08:11

Sane


Not sure if this is more idiomatic, but sometimes I find that placing the recoverWith in this manner improves readability for me:

def doDangerousThing(): Try[Result] = Try {
  dangerousOp
} recoverWith {
  case t: Throwable => println("error"); Failure(t)
}
like image 33
Alex Avatar answered Nov 29 '22 10:11

Alex