SRobertJames SRobertJames - 8 months ago 66
Scala Question

Scala - Try with exception logging

Scala's

Try
is very useful. I'd like to use that pattern, but log all exceptions. How can I do this?

Answer

Define the following helper:

import scala.util.{Try, Failure}

def LogTry[A](computation: => A): Try[A] = {
  Try(computation) recoverWith {
    case e: Throwable =>
      log(e)
      new Failure(e)
  }
}

Then you can use it as you would use Try, but any exception will be logged through log(e).