【问题标题】:Error Response 500 is not getting diaplayed when password and confirm password typed wrong当密码和确认密码输入错误时,错误响应 500 未显示
【发布时间】:2020-07-24 10:03:06
【问题描述】:

当密码和确认密码输入正确时,我的响应成功显示......需要帮助...在此先感谢

这是我在邮递员中输入错误密码和确认密码时的回复:-

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

这是我的数据类:-

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
 )

我的响应呼叫活动:--->

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

                    }
                }
            })
    }

在调试器中将 else if (res.body()?.status == 500) 替换为 else if (!res.isSuccessful ==> false

但如果我这样做-->else if (res.errorBody()?.equals(500)!!)

我得到了这个-->

这很好,但是我如何在这个[size=176 text={"status":500,"message":"Could not reset password.","error":{"co…] 下访问我在内容下的错误下有错误消息

我想检索 ==> message":"Could not reset password."error":{"co......

【问题讨论】:

  • 你检查response.isSuccessful是不是真的?
  • @shafayathossain 当密码输入错误并确认密码输入错误时我没有成功
  • 那么你无法通过这种方式得到错误响应。您必须解析错误正文。示例可以在这里找到:futurestud.io/tutorials/retrofit-2-simple-error-handling
  • @shafayathossain 看看编辑后的问题
  • @Wini 这就是你必须解析错误正文的原因。我在之前的评论中给出了一个链接。它将帮助您解析错误正文。

标签: android validation kotlin retrofit retrofit2


【解决方案1】:

您必须解析错误正文。以下代码将帮助您解析错误。

您可以创建自定义错误类,以便针对特定错误类型执行操作。两个异常类可以如下:

open class APIError: Exception() {
    private val statusCode = 0
    fun status(): Int {
        return statusCode
    }

    fun message(): String? {
        return message
    }
}

class UnknownError : APIError() {}

错误解析器类可以如下。我在这里使用了 kotling 扩展功能来轻松使用它。

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

最后在改造onResponse() 方法中,你可以这样做:

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】:

不检查正文响应错误代码检查

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

【讨论】:

  • 我根本没有烤面包......在调试过程中,我得到了上面显示的第二张图片............如果你看到,我的回复是错误正文的内容......我怎样才能找回那个????
  • 它在errorBody()里面,如果你调用response.errorBody()你应该得到,只需检查代码
  • 我只用过这个 --> l response.errorBody() .....情况还是一样
  • 你能否在 if 条件下也将这一行 (res.body()?.status == 500) 更改为 res.code()==500
  • 问题是body本身为null,如果整个body为null,如何检查状态码
【解决方案3】:

好的,所以你需要阅读 Error ResponseBody

    val errorBodyBuffer = Buffer()
    res.errorBody()?.writeTo(errorBodyBuffer)
    val errorBodyString = errorBodyBuffer.clone().readUtf8()

现在您可以使用 Gson 或 JsonObject 来解析 errorBodyString

【讨论】:

  • 没有仍然无法正常工作..我在 body==> 使用调试器时为空...
  • 异常信息是什么?
  • 我从 shafayat 那里得到了答案,分享了上面的链接。感谢您的快速回复:)
猜你喜欢
  • 1970-01-01
  • 2013-03-13
  • 2014-09-24
  • 2017-09-02
  • 2019-10-29
  • 2020-02-14
  • 1970-01-01
  • 1970-01-01
  • 2022-07-06
相关资源
最近更新 更多