How to catch exception in scala.sys.process pipe

2019-08-11 23:16发布

问题:

If I download a big file with scala.sys.process like this:

import java.io.File
import java.net.URL
import scala.sys.process._
new URL("http://www.scala-lang.org/") #> new File("scala-lang.html") !

If there is some problem during the download, the stack trace will just print at stderr but it is not caught in my try-catch block. I believe there are ways to catch the error and retry, but how do I do that?

回答1:

The sequence

new URL("http://www.scala-lang.org/") #> new File("scala-lang.html") !

evaluates to Int which corresponds to the exit code of the operation.

When it equals 0, the result is successful, otherwise there was an error.

So it can be processed as follows

val result = new URL(...)
if (result != 0) {
  throw new MyCustomException("message") // or retry
}


标签: scala