DennisVDB DennisVDB - 3 months ago 8
Scala Question

Handling null and exception from Java API call in Scala

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.

Answer

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.

Comments