Error Response 500 is not getting diaplayed when password and confirm password typed wrong

半城伤御伤魂 提交于 2020-08-17 12:19:05

问题


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......please guide me ...need help...thanks in advance

here is my response when password and confirm password typed wrong in postman:-

{
"status": 500,
"message": "Could not reset password.",
"error": {
    "confirm_password": {
        "compareWith": "Passwords mismatch."
    }
},
"user_msg": "Could not reset password, please try again."
}

here is my data classes:-

1-->

data class Reset_Reponse_Base (
@SerializedName("status") val status : Int,
@SerializedName("message") val message : String,
@SerializedName("error") val error : Reset_Response_error,
@SerializedName("user_msg") val user_msg : String
)

2-->

 data class Reset_Response_error (
@SerializedName("confirm_password") val confirm_password : Reset_Response_Confirm_password

 )

3-->

data class Reset_Response_Confirm_password (
@SerializedName("compareWith") val compareWith : String
 )

My response call activity:--->

 var old_password = findViewById<TextView>(R.id.old_password)
    var new_password = findViewById<TextView>(R.id.new_password)
    var confirm_password =
        findViewById<TextView>(R.id.confirm_new_password)
    val resetpwdbutton = findViewById<Button>(R.id.resetpwdbtn)
    resetpwdbutton.setOnClickListener {
        val old = old_password.text.toString().trim()
        val new = new_password.text.toString().trim()
        val confirm = confirm_password.text.toString().trim()
       
        val token: String =
            SharedPrefManager.getInstance(
                applicationContext
            ).user.access_token.toString()
        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 (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)
                            }
                        }

                    }
                }
            })
    }

After replacing this else if (res.body()?.status == 500) by else if (!res.isSuccessful ==> false in debugger

but if i do this-->else if (res.errorBody()?.equals(500)!!)

im getting this -->

which is good but how can i access under this [size=176 text={"status":500,"message":"Could not reset password.","error":{"co…] i have error message under error under content

i want to retrive ==> message":"Could not reset password."error":{"co…...


回答1:


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
                    }
                }
            })



回答2:


don't check the body response error code check for

if(response.code() == 500){
  val errorBody = response.errorBody()
  val json = JSONObject(errorBody)
  //show toast
}



回答3:


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



来源:https://stackoverflow.com/questions/63071359/error-response-500-is-not-getting-diaplayed-when-password-and-confirm-password-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!