现在我正在使用以下代码打开漫画书文件(.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
}
}
答案 0 :(得分:0)
我建议您查看使用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")
}
我没有测试这段代码,但也许它有所帮助。