tadamhicks
tadamhicks

Reputation: 925

Scala Try, Else, Except block

I have code like this:

val extractInfo: (Array[Byte] => String) = (fp: Array[Byte]) => {

  val parser:Parser = new AutoDetectParser()
  val handler:BodyContentHandler = new BodyContentHandler(Integer.MAX_VALUE)
  val config:TesseractOCRConfig  = new TesseractOCRConfig()
  val pdfConfig:PDFParserConfig = new PDFParserConfig()

  val inputstream:InputStream = new ByteArrayInputStream(fp)

  val metadata:Metadata = new  Metadata()
  val parseContext:ParseContext = new ParseContext()
  parseContext.set(classOf[TesseractOCRConfig], config)
  parseContext.set(classOf[PDFParserConfig], pdfConfig)
  parseContext.set(classOf[Parser], parser)
  parser.parse(inputstream, handler, metadata, parseContext)

  handler.toString
}

A function literal that parses text from PDFs using Apache Tika.

What I want, though, is a Try block in here that runs on parser.parse and returns an empty string if it cannot execute. I am not sure how to construct this sort of logic in Scala.

Upvotes: 1

Views: 2102

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170919

You can just write

try {
  val parser:Parser = new AutoDetectParser()
  val handler:BodyContentHandler = new BodyContentHandler(Integer.MAX_VALUE)
  val config:TesseractOCRConfig  = new TesseractOCRConfig()
  val pdfConfig:PDFParserConfig = new PDFParserConfig()

  val inputstream:InputStream = new ByteArrayInputStream(fp)

  val metadata:Metadata = new  Metadata()
  val parseContext:ParseContext = new ParseContext()
  parseContext.set(classOf[TesseractOCRConfig], config)
  parseContext.set(classOf[PDFParserConfig], pdfConfig)
  parseContext.set(classOf[Parser], parser)
  parser.parse(inputstream, handler, metadata, parseContext)

  handler.toString
} catch {
  case e: Exception => ""
}

because try is an expression in Scala, just like if or match. However, if you intend to use "" as a sentinel value (that is, check later whether an error happened by checking if the result is empty), don't; use Option[String] or Try[String] as the return type instead.

Upvotes: 2

Alec
Alec

Reputation: 32329

I think what you are looking for is Try.

val extractInfo: (Array[Byte] => String) = (fp: Array[Byte]) => Try {
  val parser:Parser = new AutoDetectParser()
  ...
  handler.toString
} getOrElse("")

What this does is catch any error in the body and recover from this error by returning the empty string.

Upvotes: 5

Related Questions