Jes*_*ose 3 scala playframework
我从我的请求中得到了我的回复(简单,阻塞)方式:
val response = Http(req)()
Run Code Online (Sandbox Code Playgroud)
但我从Play中得到了这个错误!框架:
ExecutionException: java.net.ConnectException: Connection refused to http://localhost:8983/update/json?commit=true&wt=json
Run Code Online (Sandbox Code Playgroud)
我从未想过Dispatch或Scala中的异常处理.在Dispatch库中我必须注意哪些错误?捕获每种类型/类错误的语句是什么?
在这种情况下处理异常的一种常见方法是使用Either[Throwable, Whatever]来表示结果,其中某种类型的失败实际上并非如此.Dispatch 0.9使用这个either方法很方便Promise(顺便说一句,我在回答你之前的问题时使用了这个方法):
import com.ning.http.client.Response
val response: Either[Throwable, Response] = Http(req).either()
Run Code Online (Sandbox Code Playgroud)
现在您可以非常自然地使用模式匹配来处理异常:
import java.net.ConnectException
response match {
case Right(res) => println(res.getResponseBody)
case Left(_: ConnectException) => println("Can't connect!")
case Left(StatusCode(404)) => println("Not found!")
case Left(StatusCode(code)) => println("Some other code: " + code.toString)
case Left(e) => println("Something else: " + e.getMessage)
}
Run Code Online (Sandbox Code Playgroud)
您还可以使用许多其他方法Either使处理失败更加方便 - 例如,请参阅此Stack Overflow应答.