Fix:Catch api handler invalid json response body

This commit is contained in:
advplyr 2022-07-15 16:22:44 -05:00
parent 066b72d54d
commit d9cdc16ff9

View file

@ -17,6 +17,7 @@ import com.getcapacitor.JSObject
import okhttp3.* import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONException
import org.json.JSONObject import org.json.JSONObject
import java.io.IOException import java.io.IOException
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
@ -106,6 +107,7 @@ class ApiHandler(var ctx:Context) {
if (bodyString == "OK") { if (bodyString == "OK") {
cb(JSObject()) cb(JSObject())
} else { } else {
try {
var jsonObj = JSObject() var jsonObj = JSObject()
if (bodyString.startsWith("[")) { if (bodyString.startsWith("[")) {
val array = JSArray(bodyString) val array = JSArray(bodyString)
@ -114,6 +116,12 @@ class ApiHandler(var ctx:Context) {
jsonObj = JSObject(bodyString) jsonObj = JSObject(bodyString)
} }
cb(jsonObj) cb(jsonObj)
} catch(je:JSONException) {
Log.e(tag, "Invalid JSON response ${je.localizedMessage} from body $bodyString")
val jsobj = JSObject()
jsobj.put("error", "Invalid response body")
cb(jsobj)
}
} }
} }
} }