Error handling for functions without a return value

50 views
Skip to first unread message

Marcel Luethi

unread,
Oct 10, 2012, 2:23:35 AM10/10/12
to scala...@googlegroups.com
Dear all, 

I am rather new to Scala and, as so many other users, am a bit confused about the "right" way to do error handling. 
I understand that I should generally avoid exceptions, and that Option or Either is the way to go. 
However, I am still confused about how I should handle failures for functions that do not return a result, such as the following:  
def writeXToFile : Unit = { 
  // some code that may fail
Here, returning an Option seems counter intuitive, as it would be None if it success and Some(errormsg) in the failure case. 
What is the recommended way to handle such cases?

Thank you very much for your help.

Marcel

Naftoli Gugenheim

unread,
Oct 12, 2012, 3:51:59 PM10/12/12
to Marcel Luethi, scala...@googlegroups.com
A Boolean?

HamsterofDeath

unread,
Oct 12, 2012, 3:59:57 PM10/12/12
to scala...@googlegroups.com
you can do:
throw an exception
make an enumeration (Failed, Ok) and return that
a boolean
use two callbacks, one for ok, one for failure (aka continuations)

Derek Williams

unread,
Oct 12, 2012, 10:45:12 PM10/12/12
to Marcel Luethi, scala...@googlegroups.com
On Wed, Oct 10, 2012 at 12:23 AM, Marcel Luethi <marcel...@gmail.com> wrote:
However, I am still confused about how I should handle failures for functions that do not return a result, such as the following:  
def writeXToFile : Unit = { 
  // some code that may fail
 
To be consistent with other methods that do actually return a value, I'd use Either, with a constant for a successful Unit result:

package object validations {
  val RightUnit = Right(Unit)

  // and perhaps add some helpers in there too to help make life easier:

  class TryRight[A](block: => A) {
    def catchLeft[B](handler: PartialFunction[Throwable, Either[B, A]]): Either[B, A] = try Right(block) catch handler
  }

  def tryRight[A](block: => A) = new TryRight(block)

}

then you can write your method like:

def writeXToFile =
  if (somecondition) {
    ... do stuff ...
    RightUnit
  } else Left("I failed!")

or

def writeXToFile = tryRight {
  ... do stuff ...
} catchLeft {
  case e: SomeException => "Failed to writeXToFile due to SomeException"
}

Which is of course kinda similar to some of what the new Try class in 2.10 does, but since you are using Either it will mean your types will carry more information about your failure type.

--
Derek Williams

Reply all
Reply to author
Forward
0 new messages