Reputation: 2518
I want to get the exact error message returned from the server in Kotlin. I am currently handling as below
Response.ErrorListener {error ->
// regProgress.hide()
val resp = error
if(error is ClientError ){
Toast.makeText(context!!.applicationContext, "User already exists", Toast.LENGTH_SHORT).show()
}
else if(error is NetworkError){
Toast.makeText(context!!.applicationContext, "Network error \nPlease check your network connection", Toast.LENGTH_SHORT).show()
}
else if(error is TimeoutError){
Toast.makeText(context!!.applicationContext, "Request time out", Toast.LENGTH_SHORT).show()
}
else if(error is AuthFailureError){
Toast.makeText(context!!.applicationContext, "Bad request \nKindly check details provided", Toast.LENGTH_SHORT).show()
}
else if(error is ServerError){
Toast.makeText(context!!.applicationContext, "Internal server error \nPlease try again", Toast.LENGTH_SHORT).show()
}
else if(error is NoConnectionError){
Toast.makeText(context!!.applicationContext, "Poor connection \n" +
"Please check your network connection", Toast.LENGTH_SHORT).show()
}
regProgressBar.visibility = View.GONE
registerBtn.visibility = View.VISIBLE
// val responseBody = error.networkResponse.data.toString()
Log.e("Data", "Response $resp")
// Log.e("Network", "Response ${error.networkResponse}")
// Toast.makeText(context!!.applicationContext, "$it", Toast.LENGTH_SHORT).show()
}
I have tried the parseNetwork method but gets error. I will really appreciate if there is a way to get the method automatically like using ctrl o
to bring up methods that can be implemented.
Upvotes: 1
Views: 542
Reputation: 2518
I was able to solve this with
if(error.networkResponse != null){
val errorByte = error.networkResponse.data
val parseError = errorByte.toString(UTF_8)
val errorObj = JSONObject(parseError)
val errorMessage = errorObj.getString("message")
Toast.makeText(context!!.applicationContext, errorMessage, Toast.LENGTH_SHORT).show()
}
Upvotes: 1