2

I have the following code (simplified):

def getSomething(name: String): MyError \/ Option[Int] = {
    /* Returns Null if name doesn't exist, IOException if connection err. */
    val output: queryDB(name)

    // ...
}

The queryDB function is a Java call.

I would like the following to happen: IOException mapped to MyError, and null to None. How should I proceed?

I am aware that I can wrap the output in an Option since null is mapped to None. However, how do I manage the exception?

Thanks.

1
  • anything wrong with try / catch? you could use scala.util.Try too, ie Try( Option( queryDB(name) ) ) but old-school try / catch might just be simpler here. Commented Aug 19, 2016 at 12:15

2 Answers 2

1

I would use a combination of Option and Try

import scala.util.{ Try, Success, Failure }

def getSomething(name: String): MyError \/ Option[Int] = {

   Try(queryDB(name)) match {
     case Success(v) => Option(v).right // in case v is null, this returns a None
     case Failure(e) => MyError().left
   }

}

This turns all exceptions into MyError. If you need specific error handling you can match on e and have more granularity.

Also I'm using .right and .left that come from the syntax package of scalaz. If you are not using those, you can replace them with \/-(Option(v)) and -\/(MyError()) respectively.

Sign up to request clarification or add additional context in comments.

2 Comments

"If you need specific error handling you can match on e and have more granularity." Does this mean to look at Throwable's getMessage?
No, I mean matching on the exception type
1

I think you need a combination of Either and Try. Using "transform" method of Try, you can convert the result to an Either[Throwable, Option[Int]]. Something along the lines of,

// Change the 2nd arg of transform to MyError as per your requirement.

def getSomething(name: String): Either[Throwable, Option[Int]] = {
    Try(queryDB(name)).transform(s => Success(Right(Option(s))), f => Success(Left(f))).get
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.