简体   繁体   中英

Exception handling Scala ARM

val res = Try (
    for (
        gzipStream <- managed((new GZIPInputStream(s3Obj.getObjectContent())));
        decoder <- managed((new InputStreamReader(gzipStream, "US-ASCII")));
        reader <- managed((new BufferedReader(decoder)))
    ) yield {
        var jsr = ""
        var eachLine = reader.readLine()
        while (eachLine != null) {
            jsr += eachLine
            eachLine = reader.readLine()
        }            
        jsr
    }
)

I am new to Scala (1 month old) I am trying to arm http://jsuereth.com/scala-arm/usage.html

When there is an exception the Try is still returning Success. How do I catch and handle the errors, According to the docs "the originating exception (from inside the for block) will be thrown and any exceptions thrown while closing the resource will be suppressed."

res is of type ManagedResource[String] .

To catch and handle the errors, you could use ManagedResource.acquireFor like this:

val res: ManagedResource[String] = for (
  gzipStream <- managed((new GZIPInputStream(s3Obj.getObjectContent())));
  decoder <- managed((new InputStreamReader(gzipStream, "US-ASCII")));
  reader <- managed((new BufferedReader(decoder)))
) yield {
  var jsr = ""
  var eachLine = reader.readLine()
  while (eachLine != null) {
    jsr += eachLine
    eachLine = reader.readLine()
  }
  jsr
}

val either: Either[List[Throwable], String] = res.acquireFor(identity)

either match {
  case Left(throwables) => ???
  case Right(string) => ???
}

But I would recommend using the monadic style:

val res = managed(new BufferedReader(new InputStreamReader(new GZIPInputStream(s3Obj.getObjectContent()), "US-ASCII"))) map {
  reader =>
    var jsr = ""
    var eachLine = reader.readLine()
    while (eachLine != null) {
      jsr += eachLine
      eachLine = reader.readLine()
    }
    jsr
}
res.either match {
  case Left(throwables) => ???
  case Right(string) => ???
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM