这个问题在这里已有答案:
我是Scala编码的新手。我有下面的代码片段,它使用documentBuilder构建文档。我的输入是XML。每当我在代码下输入格式错误的XML时,无法使用parse
并引发SAXException。
def parse_xml(xmlString: String)(implicit invocationTs: Date) : Either [None, Document] = {
try {
println(s"Parse xmlString invoked")
val document = documentBuilder(false).parse(new InputSource(new StringReader(xmlString)))
document.getDocumentElement.normalize()
//Right(document)
document
} catch {
case e: Exception => None
由于parse函数的内置实现,引发了SAXException。请参阅以下处理SAXException的代码:
public abstract Document parse(InputSource is)
throws SAXException, IOException;
现在我试图绕过这个SAXException,因为我不希望我的工作因为一个格式错误的XML而失败。所以我把try catch块处理放在异常下面:
case e: Exception => None
但它在这里显示错误为“类型无表达。类型不确认期望类型文档”,因为我的返回类型是文档。
有人可以帮助我摆脱这个问题吗?提前致谢
如果你想使用包装器,比如Either
或Option
,你总是要包装返回的值。
如果你想进一步传递异常,比Either
更好的选择可能是Try
:
def parse_xml(xmlString: String)(implicit invocationTs: Date) : Try[Document] = {
try {
println(s"Parse xmlString invoked")
val document = documentBuilder(false).parse(new InputSource(new StringReader(xmlString)))
document.getDocumentElement.normalize()
Success(document)
} catch {
case e: Exception => Failure(e)
}
}
您甚至可以通过在Try.apply
中包装块来简化它:
Try{
println(s"Parse xmlString invoked")
val document = documentBuilder(false).parse(new InputSource(new StringReader(xmlString)))
document.getDocumentElement.normalize()
document
}
如果您不关心异常,只关注结果,请使用Option
:
def parse_xml(xmlString: String)(implicit invocationTs: Date) : Option[Document] = {
try {
println(s"Parse xmlString invoked")
val document = documentBuilder(false).parse(new InputSource(new StringReader(xmlString)))
document.getDocumentElement.normalize()
Some(document)
} catch {
case e: Exception => None
}
}