scalamappingfutureflatmapplayframework-webservice

scala future null pointer match error


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?


Solution

  • 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.