Search code examples
scalascala-dispatch

How do I get the value of a failed request in Dispatch?


When I make a request in Dispatch, I apply the Promise and get this:

Left(dispatch.StatusCode: Unexpected response status: 400)

How do I get the actual text of the response? I'm using Solr and it still returns valuable JSON with failed HTTP requests.


Solution

  • It looks like you've written something like the following:

    Http(url OK as.String)
    

    The OK is what's providing the simple error handling you see here. You can use > to get the results more directly. For example, if you write this:

    Http(url("http://google.com/") OK as.String).either()
    

    You'll get the following (at the moment, at least):

    Left(dispatch.StatusCode: Unexpected response status: 301)
    

    But if you make the following small change:

    Http(url("http://google.com/") > as.String).either()
    

    You get the full body of the redirect page:

    res1: Either[Throwable,String] = 
    Right(<HTML><HEAD><meta http-equiv="content-type" ...
    

    If you want to do something fancier with the response, you can write your own asWhatever handler—see my answer here for a demonstration of how to get access to the headers as a map, for example.