"application/json").post(dataForR).fla" /> "application/json").post(dataForR).fla" /> "application/json").post(dataForR).fla"/>

scala future null pointer match error

1.3k Views Asked by At

New to scala futures I try to call a web service like

wsClient.url(baseUrl + url).withHeaders("Content-Type" -> "application/json").post(dataForR).flatMap(parseOutlierResponse)

using ply-ws library

I validate & map the response as follows https://gist.github.com/geoHeil/943a18d43279762ad4cdfe9aa2e40770

The main thing is:

Await.result(callAMethodCallingTheFirstSnippet, 5.minutes)

Strangely this works just fine in the repl. However if run via sbt run I get a NullPointer Exception. I already verified the JSON response manually. It validates like a breeze. Even the mapping works great. However, there must be a problem with the futures I am using. But I am not sure what is wrong. It seems like the flatMap method is called before there already is a result.

Interestingly if I do not await the result there is no null-pointer exception, but the parsed result is displayed correctly (however, the program does not exit). But there, where I really use this code, I somehow need to await the successful completion to further deal with it.

Below you will find an illustration of the problem

How can the response body be null?

2

There are 2 best solutions below

2
Georg Heiler On BEST ANSWER

After more and more debugging I found that some implicits were in the wrong scope and the order of dependent case-classes was wrong. After moving them into the correct scope (the method performing the request) the null-pointer exception is fixed.

I could only find the "real" error after changing from flatmap to map which I find very strange. However, now both methods work fine.

1
joesan On

I do not see any major concern with your code! I made a small test with the following code bit and it seems to be working perfectly, both in the REPL and when using sbt run:

    WS.clientUrl(s"http://$hostName/api/put").withHeaders(jsonHeaders: _*).post(body).map { r =>
      if (r.status >= 400)
        logger.warn(s"Invalid http response status: ${r.status} \n ${r.body}")
      else
        logger.debug(s"Successfully persisted data. Http response ${r.status}")
    }