From bbf28ad69295b96724aa28958ab016e5f21deb1e Mon Sep 17 00:00:00 2001 From: "Erik C. Thauvin" Date: Mon, 3 Jan 2022 11:51:31 -0800 Subject: [PATCH] Improved response parsing. --- cryptoprice.iml | 6 +++++ .../net/thauvin/erik/crypto/CryptoPrice.kt | 24 ++++++++----------- 2 files changed, 16 insertions(+), 14 deletions(-) create mode 100644 cryptoprice.iml diff --git a/cryptoprice.iml b/cryptoprice.iml new file mode 100644 index 0000000..ecfedb7 --- /dev/null +++ b/cryptoprice.iml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/src/main/kotlin/net/thauvin/erik/crypto/CryptoPrice.kt b/src/main/kotlin/net/thauvin/erik/crypto/CryptoPrice.kt index f3dbc95..399c8fa 100644 --- a/src/main/kotlin/net/thauvin/erik/crypto/CryptoPrice.kt +++ b/src/main/kotlin/net/thauvin/erik/crypto/CryptoPrice.kt @@ -102,21 +102,17 @@ open class CryptoPrice(val base: String, val currency: String, val amount: BigDe val request = Request.Builder().url(httpUrl).build() val response = client.newCall(request).execute() - val body = response.body?.string() - if (body != null) { - try { - val json = JSONObject(body) - if (response.isSuccessful) { - return body - } else { - val data = json.getJSONArray("errors") - throw CryptoException(response.code, data.getJSONObject(0).getString("message")) - } - } catch (e: JSONException) { - throw CryptoException(response.code, "Could not parse data.", e) + val body = response.body?.string() ?: throw CryptoException(response.code, "Empty response.") + try { + val json = JSONObject(body) + if (response.isSuccessful) { + return body + } else { + val data = json.getJSONArray("errors") + throw CryptoException(response.code, data.getJSONObject(0).getString("message")) } - } else { - throw CryptoException(response.code, "Empty response.") + } catch (e: JSONException) { + throw CryptoException(response.code, "Could not parse data.", e) } }