现在我正在用下面的代码打开漫画文件(.cbr & cbz),但我觉得可以做得更好。你会怎么做呢?
@throws(classOf[Exception])
def extract(filePath: String): File = {
val unZip = new runCommand(Seq("7z", "x", "-y", filePath, s"-o${tempLocation}"))
if (unZip.exitValue == 0){
new File(tempLocation)
}else{
throw new Exception(unZip.errValue)
}
}
@throws(classOf[Exception])
def preExtract(filePath: String): File = {
try {
filePath.split("\\.").last match {
case "cbz" => extract(filePath)
case "cbr" => extract(filePath)
case _ =>
throw new FileNotFoundException("Incorrect file extension for file: " + filePath)
}
} catch {
case ex: Exception =>
throw ex
}
}发布于 2016-07-11 11:54:50
我建议你使用scala.util.Try,而不是捕捉和重新抛出异常。Here是一篇关于这个主题的很好的文章。
现在,我不熟悉您使用的runCommand()函数,也许它是您自己的函数?在这种情况下,您可以修改它以返回包装在Option中的错误代码,如果没有发生错误,则返回None。如果是这样的话,您的代码段可以实现为具有两个嵌套match块的单个函数:
def extract(filePath: String): Try[File] = filePath match {
case str if str.endsWith(".cbz") || str.endsWith(".cbr") =>
runCommand(Seq(...)) match {
case None => new File(tempLocation)
case Some(errValue) => throw new UnzipFailedException(errValue)
}
case _ => throw new InvalidArgumentException(s"Incorrect file extension for file: $filePath")
}我没有测试这段代码,但它可能会有一些帮助。
https://stackoverflow.com/questions/38297940
复制相似问题