我有以下代码向HTTP服务请求获取资源。可能是服务不可用或资源不可用。所以我需要处理这样的错误情况。服务器实际上抛出了我必须在我的Scala客户端中处理的异常。以下是我到目前为止所做的事情:
def getData(resource: String, requestParam: Option[Seq[(String, String)]]): Try[Elem] = {
Try {
val wc = WebClient.create(address(scheme, host, port) + "/" + resource, un, pw, null)
// Load the trust store to the HTTPConduit
if ("https" == scheme) {
val conduit = WebClient.getConfig(wc).getConduit.asInstanceOf[HTTPConduit]
loadTrustStore(conduit)
}
requestParam match {
case Some(reqParams) => reqParams.foreach((param: (String, String)) => {
wc.query(param._1, param._2)
})
case None => wc
}
XML.loadString("""<?xml version="1.0" encoding="UTF-8"?>""" + wc.get(classOf[String]))
}
}
现在,此方法的调用者如下所示:
def prepareDomainObject(): MyDomainObject = {
getData(resource, params) match {
case Success(elem) => getDomainFromElem(elem)
case Failure(_) => ?? What do I do here? I actually want to get the message in the Throwable and return another type. How do I get around this?
}
如何处理匹配条件,以便在出现错误时返回其他类型?
答案 0 :(得分:2)
您有两种选择。要么prepareDomainObject
也要返回Try
:
def prepareDomainObject(): Try[MyDomainObject] = {
getData(resource, params) map getDomainFromElem
}
或者在错误时抛出异常:
def prepareDomainObject(): MyDomainObject = {
getDomainFromElem(getData(resource, params).get)
}