How can I retrieve the errorBody sent from server on retrofit error handler?

99封情书 提交于 2021-01-29 08:31:13

问题


When everything goes well, I can retrieve the body from response.body() with no problem.

Althought, when a validation error occurs on server (in my case, duplicated email) it sends the error to frontend and when I try to access the error body response.errorBody() the following info is retrieved:

"E/API Activity: onResponse: PostSalao okhttp3.ResponseBody$1@84d856e"

I expected to get something like "error: email already used".

As you may see on this video on (10:08), he does the same thing I'm doing on my code, but he retrieves the erros correctly (10:17).

What am I doing wrong?

fun postCliente(cliente: Cliente) {
        val TAG = "API Activity"
        val apiInterface: ApiInterface
        apiInterface = ClientApi.getClient().create(ApiInterface::class.java)
        val clientePostCall = apiInterface.postCliente(cliente)
        mProgressBar.visibility = View.VISIBLE

        clientePostCall.enqueue(object: Callback<Cliente> {
            override fun onResponse(call: Call<Cliente>, response: Response<Cliente>) {
                mProgressBar.visibility = View.GONE
                if(response.isSuccessful){
                    try {
                    Toast.makeText(context,"Usuario " + response.body()!!.name + " criado com sucesso.",Toast.LENGTH_SHORT).show()
                        val backHomeIntent = Intent(context, MainActivity::class.java)
                        context.startActivity(backHomeIntent)
                    } catch (e: NullPointerException) {
                        Toast.makeText(context, "Problem is unknown: ", Toast.LENGTH_SHORT).show()
                    }
                }else {
                    try {
                        val errorBody = response.errorBody().toString()


                        Toast.makeText(context, "Dados incorretos", Toast.LENGTH_SHORT).show()
                            Log.e(TAG, "onResponse: " + errorBody )

                    } catch (e: IOException){
                        Toast.makeText(context, "Problem is unknown: ", Toast.LENGTH_SHORT).show()
                    }
                }
            }
            override fun onFailure(call: Call<Cliente>, t: Throwable) {
                mProgressBar.visibility = View.GONE
                Log.e(TAG, "onFailure: " + t.localizedMessage)
            }
        })
    }

Logcat on Android in red


回答1:


You have to use string() rather than toString() to get the correct error message. So your code would look something like this:

fun postCliente(cliente: Cliente) {
    val TAG = "API Activity"
    val apiInterface: ApiInterface
    apiInterface = ClientApi.getClient().create(ApiInterface::class.java)
    val clientePostCall = apiInterface.postCliente(cliente)
    mProgressBar.visibility = View.VISIBLE

    clientePostCall.enqueue(object: Callback<Cliente> {
        override fun onResponse(call: Call<Cliente>, response: Response<Cliente>) {
            mProgressBar.visibility = View.GONE
            if(response.isSuccessful){
                try {
                Toast.makeText(context,"Usuario " + response.body()!!.name + " criado com sucesso.",Toast.LENGTH_SHORT).show()
                    val backHomeIntent = Intent(context, MainActivity::class.java)
                    context.startActivity(backHomeIntent)
                } catch (e: NullPointerException) {
                    Toast.makeText(context, "Problem is unknown: ", Toast.LENGTH_SHORT).show()
                }
            }else {
                try {
                    val errorBody = response.errorBody().string()


                    Toast.makeText(context, "Dados incorretos", Toast.LENGTH_SHORT).show()
                        Log.e(TAG, "onResponse: " + errorBody )

                } catch (e: IOException){
                    Toast.makeText(context, "Problem is unknown: ", Toast.LENGTH_SHORT).show()
                }
            }
        }
        override fun onFailure(call: Call<Cliente>, t: Throwable) {
            mProgressBar.visibility = View.GONE
            Log.e(TAG, "onFailure: " + t.localizedMessage)
        }
    })
}


来源:https://stackoverflow.com/questions/55834843/how-can-i-retrieve-the-errorbody-sent-from-server-on-retrofit-error-handler

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