简体   繁体   English

为成功和失败改造处理 2 个不同的错误响应

[英]handle 2 different error response for success and failer retrofit2

My current success response is this:我目前的成功响应是这样的:

{"status":"success","message":"msg here"}

with code 200带代码 200

And my error response is this:我的错误响应是这样的:

{"status":"failure","message":"There was a validation error","errors":{"shippingAddress":{"phoneNumber":"Please enter a valid phone number"}}}

with code 400带代码 400

my problem is the code below is not working because it always go inside onFailure()我的问题是下面的代码不起作用,因为它总是 go 在 onFailure()

        if (response.isSuccessful()) {
            // do something

        } else if (response.code() == 400) {
            Gson gson = new Gson();
            ErrorPhone message = null;
            if (response.errorBody() != null) {
                message = gson.fromJson(response.errorBody().charStream(), ErrorPhone.class);
            }
            if (message != null) {
                Toast.makeText(context, message.getErrors().getShippingAddress().getPhoneNumber(), Toast.LENGTH_LONG).show();
            } else {
                String errors = "";
                try {
                    JSONObject jObjError = new JSONObject(response.errorBody().string());
                    errors = jObjError.getJSONObject("errors").getJSONObject("shippingAddress").getString("phoneNumber");
                } catch (JSONException | IOException e) {
                    e.printStackTrace();
                }
                if (!errors.equals("")) {
                    Toast.makeText(context, errors, Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(context, response.message(), Toast.LENGTH_LONG).show();
                }
            }
        }

and inside onFailure i cant listen to errorBody to handle the response在 onFailure 里面我不能听 errorBody 来处理响应

Use Retrofit interface called onResponse and place your code there.使用名为onResponseRetrofit接口并将您的代码放在那里。 As Retrofit uses two different callback methods for the two possible outcomes of a network requests: either a failure or a successful request.Retrofit使用两种不同的callback方法来处理网络请求的两种可能结果:失败成功请求。 Retrofit will call the appropriate callback method depending on the result. Retrofit会根据结果调用相应的回调方法。 If the request was successful, Retrofit will also pass you the response of the server.如果请求成功,Retrofit 也会将服务器的响应传给你。

For more view this link: https://square.github.io/retrofit/2.x/retrofit/retrofit2/Callback.html and https://futurestud.io/tutorials/java-basics-for-retrofit-callbacks that will help you more to learn about retrofit Call-backs For more view this link: https://square.github.io/retrofit/2.x/retrofit/retrofit2/Callback.html and https://futurestud.io/tutorials/java-basics-for-retrofit-callbacks that将帮助您更多地了解Call-backs回调

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

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