3

I get my response from my requests this (simple, blocking) way:

val response = Http(req)()

But I got this error from Play! framework:

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

I have never thought about exception handling in Dispatch or Scala for that matter. What are the errors i must watch for in Dispatch library? What is the statement to catch each type/ class of errors?

Jesvin Jose
  • 22,498
  • 32
  • 109
  • 202

1 Answers1

6

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.

Community
  • 1
  • 1
Travis Brown
  • 138,631
  • 12
  • 375
  • 680
  • 2
    Is there a way to get the response body, when other than 200 HTTP code is returned? – Patrik Beck Nov 26 '14 at 10:02
  • Hi, does the pattern match there wait or block until you get a response, like if you use a for comprehension? I'm a bit confused about if its safe to use this solution. Thanks! – chaotive Oct 13 '16 at 13:48