Scala Distribution Library: How to handle connection failure or timeout?

I used the Databinder distribution library in the client for a simple REST-ish API. I know how to determine if I received an HTTP request with an error status:

Http x (request) { case (200, _, _, content) => successResult(content()) case (404, _, _, _) => notFoundErrorResult case (_, _, _, _) => genericErrorResult } 

But how can I distinguish an error response from a refusal to receive any answer at all because of an invalid domain or inability to connect? And is there a way to implement a timeout when using synchronous semantics? If there is anything important in the API, I skipped it.

+7
source share
3 answers

There is also a more elegant way to configure the client using the Http.configure method, which receives the Builder => Builder function as an argument:

 val http = Http.configure(_.setAllowPoolingConnection(true).setConnectionTimeoutInMs(5000)) 
+15
source

The periodic table tells us that >! sets an exception listener, and a recent mailing list thread explains how to set a timeout .

So you can do something like:

 val http = new dispatch.Http { import org.apache.http.params.CoreConnectionPNames client.getParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 2000) client.getParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000) } http(req >! { case e => // ... }) 

Please note that I have not tested this ...

+4
source

If you are using Dispatch reboot (with AsyncHttpClient as the base library), you can configure the client configuration:

 val myHttp = new dispatch.Http { import com.ning.http.client._ val builder = new AsyncHttpClientConfig.Builder() builder.setCompressionEnabled(true) .setAllowPoolingConnection(true) .setRequestTimeoutInMs(5000) override lazy val client = new AsyncHttpClient(builder.build()) } 

and then just use this new object, as if you were using http :

 myHttp((url(baseUrl) <<? args) OK as.xml.Elem).either 
+3
source

All Articles