Scala Try elegant error behavior

Is there a more elegant way to do this in scala?

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

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

  result
}
+3
source share
9 answers

I think your statement if is absolutely true. Here is another alternative:

def doTheDangerousThing(): Try[Result] = Try(dangerousOp) recoverWith {
    case exception => println("error"); Failure(exception)
}
+10
source

Something like that:

   def doTheDangerousThing[Result](dangerousOp: =>Result): Try[Result] = Try(dangerousOp) match {
    case o @ Failure(_) =>  println("error"); o
    case _ => _
  }
+4
source

, , , recoverWith :

def doDangerousThing(): Try[Result] = Try {
  dangerousOp
} recoverWith {
  case t: Throwable => println("error"); Failure(t)
}
+4

,

def doTheDangerousThing(): Option[Result] = Try (dangerousOp) toOption

Try , Some(value), None.

Try Scala 2.10.0.

+2

. :

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

  result.failed foreach { _ =>
     println("error")
  }

  result
}

, result, :

def doTheDangerousThing(): Try[Result] = {
  Try(dangerousOp) recover {
    case ex => println("error"); throw ex
  }
}
+1

, :

  def retrieveData(dataId: String): Try[String] = {
    Try {
      Option(someApi(dataId))
        .getOrElse(throw SomeApiFailedException("invalid dataId"))
    } recoverWith {
      case e: SomeApiFailedException => Failure(e)
      case e: Throwable => Failure(SomeApiFailedException("failed retrieve dataId"))
    }
  }

  case class SomeApiFailedException(err: String) extends RuntimeException(err)
+1

, , - :

def doTheDangerousThing(): Option[Result] = 
  Try(dangerousOp) match {
    case Success(result) => Some(result)
    case Failure(e) => None //might want to log the error as well
  }
0

, , :

  • (doTheDangerousThing1)
  • (doTheDangerousThing2)
  • (doTheDangerousThing3)

:

import scala.util.{Try,Success,Failure}
object temp {
  type Result = Int

  def dangerousOp = {
    val r = scala.util.Random.nextInt(10)
    if (r > 5) r else throw new RuntimeException("Failed on " + r)
  }
  def logMessage[T](t: T) = println(t)

  def doTheDangerousThing1(): Try[Result] = Try(dangerousOp)

  def doTheDangerousThing2(): Option[Result] = {
    Try(dangerousOp) match {
      case Success(r) => Option(r)
      case _ => None
    }
  }


  def doTheDangerousThing3(): Try[Result] = {
    Try(dangerousOp) match {
      case t @ Success(r) => t
      case t @ _ => logMessage("failed: "+t); t
    }
  }
}

REPL

scala> doTheDangerousThing1
res0: scala.util.Try[Result] = Success(9)

scala> doTheDangerousThing1
res1: scala.util.Try[Result] = Success(9)

scala> doTheDangerousThing2
res2: Option[Result] = None

scala> doTheDangerousThing2
res3: Option[Result] = Some(7)

scala> doTheDangerousThing3
failed: Failure(java.lang.RuntimeException: Failed on 0)
res4: scala.util.Try[Result] = Failure(java.lang.RuntimeException: Failed on 0)

scala> doTheDangerousThing3
failed: Failure(java.lang.RuntimeException: Failed on 0)
res5: scala.util.Try[Result] = Failure(java.lang.RuntimeException: Failed on 0)
0

, foreach, , @vptheron, :

implicit class EnhancedTry[T](t: Try[T]) {
  def forfailed[U](f: Throwable => U): Unit = t match {
    case Failure(e) => f(e)
    case _ => ()
  }
}

val t = Try {
  throw new Exception("An error")
}

t.forfailed(e => println(e.getMessage))

// or use pattern matching

t.forfailed {
  case e : NullPointerException => println("NPE " + e.getMessage)
  case e => println("Other " + e.getMessage)
}

The type f: Throwable => Ucan also be Throwable => Unit, but I imitate the type of the return value of the function parameter on foreach. I can’t understand why it has a common return type instead of Unit.

0
source

All Articles