Improved response parsing.

This commit is contained in:
Erik C. Thauvin 2022-01-03 11:51:31 -08:00
parent e847e84728
commit bbf28ad692
2 changed files with 16 additions and 14 deletions

6
cryptoprice.iml Normal file
View file

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<module version="4">
<component name="MavenCustomPomFilePath">
<option name="mavenPomFileUrl" value="file://$MODULE_DIR$/pom.xml.asc" />
</component>
</module>

View file

@ -102,21 +102,17 @@ open class CryptoPrice(val base: String, val currency: String, val amount: BigDe
val request = Request.Builder().url(httpUrl).build() val request = Request.Builder().url(httpUrl).build()
val response = client.newCall(request).execute() val response = client.newCall(request).execute()
val body = response.body?.string() val body = response.body?.string() ?: throw CryptoException(response.code, "Empty response.")
if (body != null) { try {
try { val json = JSONObject(body)
val json = JSONObject(body) if (response.isSuccessful) {
if (response.isSuccessful) { return body
return body } else {
} else { val data = json.getJSONArray("errors")
val data = json.getJSONArray("errors") throw CryptoException(response.code, data.getJSONObject(0).getString("message"))
throw CryptoException(response.code, data.getJSONObject(0).getString("message"))
}
} catch (e: JSONException) {
throw CryptoException(response.code, "Could not parse data.", e)
} }
} else { } catch (e: JSONException) {
throw CryptoException(response.code, "Empty response.") throw CryptoException(response.code, "Could not parse data.", e)
} }
} }