简体   繁体   English

如何在 Kotlin 的 Volley 中解析来自服务器的错误

[英]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.我想在 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.我尝试了 parseNetwork 方法,但出现错误。 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.如果有一种方法可以自动获取方法,例如使用ctrl o出可以实现的方法,我将非常感激。

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

        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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