my response getting successfully displayed when password and confirm password typed right....but when it mismatched it is not going to else part....not showing toast anything...
Okay so you need to read the Error ResponseBody
val errorBodyBuffer = Buffer()
res.errorBody()?.writeTo(errorBodyBuffer)
val errorBodyString = errorBodyBuffer.clone().readUtf8()
Now you can use Gson or JsonObject to parse the errorBodyString
You have to parse error body. Following code will help you to parse error.
You can create your custom error class, so that you can do things for specific error type. Two exception class can be as following:
open class APIError: Exception() {
private val statusCode = 0
fun status(): Int {
return statusCode
}
fun message(): String? {
return message
}
}
class UnknownError : APIError() {}
Error parser class can be as following. I've used here kotling extension function to use it easily.
fun Response<*>.parseError(): Throwable {
val converter: Converter<ResponseBody, APIError?> = RetrofitClient.instance
.responseBodyConverter(APIError::class.java, arrayOfNulls<Annotation>(0))
val error: APIError?
error = try {
if(errorBody() != null) {
converter.convert(errorBody())
} else {
return UnknownError("Something wrong")
}
} catch (e: IOException) {
return APIError()
}
return Throwable(error)
}
And finally in retrofit onResponse()
method, you can do this:
RetrofitClient.instance.resetpassword(token, old, new, confirm)
.enqueue(object : Callback<Reset_Reponse_Base> {
override fun onFailure(call: Call<Reset_Reponse_Base>, t: Throwable) {
Log.d("res", "" + t)
}
override fun onResponse(
call: Call<Reset_Reponse_Base>,
response: Response<Reset_Reponse_Base>
) {
var res = response
if(response.isSuccessful) {
if (res.body().status == 200) {
Log.d("response check ", "" + response.body()?.status.toString())
if (res.body()?.status == 200) {
Toast.makeText(
applicationContext,
res.body()?.user_msg,
Toast.LENGTH_LONG
).show()
Log.d("kjsfgxhufb", response.body()?.user_msg.toString())
} else if (res.body()?.status == 500) {
val ret: Reset_Response_error = res.body()!!.error
val ret2: Reset_Response_Confirm_password = ret.confirm_password
//confused over here-->
//toast is not getting diaplayed when password and confirm password doesnt match
try {
val jObjError =
JSONObject(response.errorBody()!!.string())
Toast.makeText(
applicationContext,
jObjError.getString("message") + jObjError.getString("user_msg"),
Toast.LENGTH_LONG
).show()
} catch (e: Exception) {
Toast.makeText(applicationContext, e.message, Toast.LENGTH_LONG).show()
Log.e("errorrr", e.message)
}
}
}
} else {
val error = res.parseError()
// do your stuffs with error
}
}
})
don't check the body response error code check for
if(response.code() == 500){
val errorBody = response.errorBody()
val json = JSONObject(errorBody)
//show toast
}