派遣错误处理

时间:2012-09-22 17:35:00

标签: scala playframework

我的请求得到了我的回复(简单,阻塞)方式:

val response = Http(req)()

但是我从Play中得到了这个错误!框架:

ExecutionException: java.net.ConnectException: Connection refused to http://localhost:8983/update/json?commit=true&wt=json

我从未想过Dispatch或Scala中的异常处理。在Dispatch库中我必须注意哪些错误?捕获每种类型/类错误的语句是什么?

1 个答案:

答案 0 :(得分:6)

在这种情况下处理异常的一种常见方法是使用Either[Throwable, Whatever]来表示结果,其中某种类型的失败实际上并非如此。使用either上的Promise方法(顺便说一下,我在my answer to your earlier question中使用),调度0.9使这方便了:

import com.ning.http.client.Response

val response: Either[Throwable, Response] = Http(req).either()

现在您可以非常自然地使用模式匹配来处理异常:

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)
}

还有许多其他方法可以使用Either使处理失败更加方便 - 例如this Stack Overflow answer

相关问题