Skip to content

Instantly share code, notes, and snippets.

@arschles
Created October 2, 2013 23:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arschles/6802182 to your computer and use it in GitHub Desktop.
Save arschles/6802182 to your computer and use it in GitHub Desktop.
val httpClient: HttpClient = ???
val httpResponse: HttpResponse = Await.result(httpClient.get(someUrl, someHeaders).apply(), 1.second)
//bodyAsIfResponseCode will return a Success if:
//- the HttpResponse returned with HttpResponseCode.OK
//- the function in the second argument returned a Success
val bodyValidation1: Validation[Throwable, String] = httpResponse.bodyAsIfResponseCode(HttpResponseCode.OK,
{ httpResponse: HttpResponse =>
Success(httpResponse.bodyString)
}
)
val bodyValidation2: Validation[Throwable, Int] = httpResponse.bodyAsIfResponseCode(HttpResponseCode.OK,
{ httpResponse: HttpResponse =>
try {
//toInt will throw if the String isn't a valid integer
Success(httpResponse.bodyString().toInt)
} catch {
case t: Throwable => Failure(t)
}
}
)
//here we want to fail if:
//- the response code is not 404
//- the response code is 404 but it doesn't have the special 404 page
//this code could be useful for testing
val bodyValidation3: Validation[Throwable, Unit] = httpResponse.bodyAsIfResponseCode(HttpResponseCode.NotFound,
{ httpResponse: HttpResponse =>
val bodyStr = httpResponse.bodyString()
if(bodyStr != "fail sea otter") {
Failure(new Exception("what do you call a failure to fail?")
} else {
Success(())
}
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment