How to handle error or return value

I want to test, if the value is a Throwable, if it is, I want to print out an error message.

If the value is not a Throwable, I want to return it.

I have this code, which gives me following error message, when Im hovering over the “value” which sould be returned in the last line:

Found: (value : Either[Throwable, A]) Required: A )


def throwAndPlayAgainOrGet[A](value: Either[Throwable, A]): A =
{
    if(value.isLeft) println("error: " + value) + playAgain
    value
}

My Question:

how can I do that?

also asked at scala - How to handle error or return value with a method - Stack Overflow

1 Like

You can… throw the throwable, if you want: (this gets rid of the type issue)

def fun[A](value: Either[Throwable, A]): A =
  value match {
    case Left(ex) => { println("error: ..."); throw ex }
    case Right(v) => v
  }

Or you can return some default value of type A, whatever it is (up to you, without knowing more about what you’re doing I can’t say much more):

def fun[A](value: Either[Throwable, A]): A =
  value match {
    case Left(ex) => { println("error: ..."); yourDefaultValue }
    case Right(v) => v
  }

If you don’t want to actually throw anything, then you might want to use Try instead. This is the more functional approach where everything is handled with types instead of throwing exceptions:

import scala.util._
def fun[A](value: Either[Throwable, A]): Try[A] =
  value match {
    case Left(ex) => { println("error: ..."); Failure(ex) }
    case Right(v) => Success(v)
  }

Or you could design your program so that value itself is a Try[A] before it reaches your function. If you have some default value of type A (like, if A is Int maybe default value is 0, it’s your choice) then you can use getOrElse:

// here value has type Try[A]
value.getOrElse { println("error: ..."); defaultValue }

There are many options, I’m sure others can point out even better designs. I highly recommend Lessons 39 and 40 in “Get Programming with Scala” by Daniela Sfregola, I took the ideas mostly from there.

2 Likes