简体   繁体   English

Volley 无法从服务器获取错误,但向我展示了 volley 错误侦听器为什么?

[英]Volley cant get error from server but shows me volley error listener why?

I need help in resolving Volley library error.我需要帮助解决 Volley 库错误。 I have send some credentials to the server using nodejs api for user registration.我已经使用 nodejs api 向服务器发送了一些凭据以进行用户注册。 In success case, when my all credentials are unique for creating new user account, it shows me everything right all responses and etc. But when i send some duplicate credentails, means email of new user same with the email of another user, it cant show me error of server that i have get in response from server using checks but it shows me volley error listener error.在成功的情况下,当我的所有凭据对于创建新用户帐户都是唯一的时,它会向我显示所有正确的所有响应等。但是当我发送一些重复的凭据时,意味着新用户的 email 与另一个用户的 email 相同,它无法显示我使用检查从服务器得到响应的服务器错误,但它显示了凌空错误侦听器错误。

I want to show here error from server not error from volley error listener.Kindly Give me solution im stuck now.我想在这里显示来自服务器的错误而不是来自凌空错误侦听器的错误。请给我解决方案,我现在卡住了。

Code is given below:代码如下:

  register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (firstName.getText().toString().isEmpty() || firstName.getText().toString().length() <= 3){
                    Toast.makeText(getContext(), "First name length is too short", Toast.LENGTH_SHORT).show();
                }
                else if (lastName.getText().toString().isEmpty() || lastName.getText().toString().length() <= 2){
                    Toast.makeText(getContext(), "Last name length is too short", Toast.LENGTH_SHORT).show();
                }
                else if (emailUser.getText().toString().isEmpty() || !emailUser.getText().toString().trim().matches(emailPattern)){
                    Toast.makeText(getContext(), "Enter valid email address", Toast.LENGTH_SHORT).show();
                }
                else if (mobileNumber.getText().toString().isEmpty() || mobileNumber.getText().toString().length() <= 8){
                    Toast.makeText(getContext(), "Enter valid mobile number", Toast.LENGTH_SHORT).show();
                }
                else if (dobUser.getText().toString().isEmpty()){
                    Toast.makeText(getContext(), "Select date of birth", Toast.LENGTH_SHORT).show();
                }
                else if (genderUser.getText().toString().isEmpty()){
                    Toast.makeText(getContext(), "Select gender", Toast.LENGTH_SHORT).show();
                }
                else if (passwordUser.getText().toString().isEmpty() || !passwordUser.getText().toString().trim().matches(PASSWORD_PATTERN)){
                    Toast.makeText(getContext(), "Enter valid password.Password must be 1 special character 1 lower letter and 1 Upper letter and 1 Number digit", Toast.LENGTH_SHORT).show();
                }
                else {
                    registerUser();
                }

            }
        });

Here is function where error cant show properly that i want, i also use check in the code:这是 function 错误无法正确显示我想要的,我也在代码中使用检查:

private void registerUser() {

            final ProgressDialog progress = new ProgressDialog(getContext());
            progress.setTitle("Register Account");
            progress.setMessage("Loading...");
            progress.setCancelable(false);
            progress.show();

            RequestQueue queue = Volley.newRequestQueue(getContext());

            final JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("first_name", firstName.getText().toString());
                jsonObject.put("last_name",lastName.getText().toString());
                jsonObject.put("email", emailUser.getText().toString());
                jsonObject.put("password", passwordUser.getText().toString());
                jsonObject.put("gender",genderUser.getText().toString());
                jsonObject.put("phone_number", mobileNumber.getText().toString());
                jsonObject.put("date_of_birth", dobUser.getText().toString());

                JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject,
                        new Response.Listener<JSONObject>() {
                            @Override
                            public void onResponse(JSONObject response) {

                                try {
                                    String status = response.getString("status");
                                    String message = response.getString("message");

                                    if (status.equals("Success")){
                                        progress.dismiss();
                                        Toast.makeText(getContext(), response.toString(), Toast.LENGTH_SHORT).show();
                                    }
                                    else if (status.equals("Fail")){
                                        JSONArray jsonArray = response.getJSONArray("data");
                                        JSONObject jsonObject1 = jsonArray.getJSONObject(0);
                                        String error = jsonObject1.getString("error");
                                        progress.dismiss();
                                        Toast.makeText(getContext(), error.toString(), Toast.LENGTH_SHORT).show();

                                    }
                                    else {

                                        progress.dismiss();
                                        Toast.makeText(getContext(), "Something went wrong.Please try again", Toast.LENGTH_SHORT).show();

                                    }

                                } catch (JSONException e) {
                                    e.printStackTrace();
                                    Toast.makeText(getContext(), e.toString(), Toast.LENGTH_SHORT).show();
                                }

                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        progress.dismiss();
                        Toast.makeText(getContext(), "Email or mobile number already used by other account.", Toast.LENGTH_SHORT).show();
                        error.printStackTrace();
                    }
                }) {
                    @Override
                    public Map<String, String> getHeaders() {
                        Map<String, String> params = new HashMap<String, String>();
                        params.put("Content-Type", "application/json");
                        return params;
                    }
                };

//                RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
//                queue.add(request);

                queue.add(jsonRequest);


            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(getContext(), "Here is the error", Toast.LENGTH_SHORT).show();
            }


        }

This is error json response from server:这是来自服务器的错误 json 响应:

{
    "status": "Fail",
    "message": "Invalid Request",
    "data": [
        {
            "error": "Email already used by another account!"
        }
    ]
}

This is the line i have in my onErrorResponse method这是我在 onErrorResponse 方法中的行

            String result = Global.parseError(error.networkResponse.statusCode, error.networkResponse.data);

This is what i have in my parseError method.这就是我的 parseError 方法中的内容。

  public static String parseError(int responseCode, byte[] data) {

    StringBuilder stringBuilder = new StringBuilder();

    if (data == null)
        return null;
    else {

        if (responseCode == 400 || responseCode == 401 || responseCode == 402 || responseCode == 403 || responseCode == 404) {
            String string = new String(data);
            Log.d(TAG, "parseError: "+string);
            try {
                JSONObject jsonObject = new JSONObject(string);
                Log.d(TAG, "parseError: " + jsonObject);
                if (jsonObject.has("message") && !jsonObject.isNull("message"))
                    stringBuilder.append(jsonObject.getString("message"));

                if (jsonObject.has("result") && !jsonObject.isNull("result")) {

                    JSONObject resultObj = jsonObject.getJSONObject("result");

                    if (resultObj.has("errors") && !resultObj.isNull("errors")) {
                        JSONArray errorsArray = resultObj.getJSONArray("errors");

                        if (errorsArray.length() > 0) {
                            JSONObject errObj = errorsArray.getJSONObject(0);
                            if (errObj.has("message") && !errObj.isNull("message"))
                                return stringBuilder.append(errObj.getString("message")).toString();
                        }
                    }
                }
                return stringBuilder.toString();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            return String.valueOf(stringBuilder.append("We are facing server issues please try again."));
        }

    }

    return null;
}

Notice these statusCode will give you int of error code could be 400, 401 and so on.请注意,这些 statusCode 将为您提供 int 错误代码,可能是 400、401 等。

error.networkResponse.statusCode

and this is will give you the error response if present.如果存在,这将为您提供错误响应。

error.networkResponse.data

in your situation try to print the data and see if you are getting the status code and data if you have both things then you could write your method to parse the error like i did according to your error message format.在您的情况下,尝试打印数据并查看您是否正在获取状态代码和数据,如果您有这两种情况,那么您可以编写您的方法来解析错误,就像我根据您的错误消息格式所做的那样。

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

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