One common way of handling exceptions in this kind of situation, where failure of some kind isn't actually that exceptional, is to use Either[Throwable, Whatever]
to represent the result. Dispatch 0.9 makes this convenient with the either
method on Promise
(which I use in my answer to your earlier question, by the way):
import com.ning.http.client.Response
val response: Either[Throwable, Response] = Http(req).either()
Now you can very naturally use pattern matching to handle exceptions:
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)
}
There are also many other ways that you can use Either
to make handling failures more convenient—see for example this Stack Overflow answer.