简体   繁体   中英

How to parse error coming from the server in Volley in Kotlin

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.

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

        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM