【问题标题】:Error handling in a Mock Api Using Retrofit使用 Retrofit 在 Mock Api 中处理错误
【发布时间】:2019-12-22 15:59:28
【问题描述】:

我正在使用改造和模拟 api 进行测试,我已经有一个 recyclerview,其中包含产品列表和产品的详细信息,同时单击该行,但在某些产品中,josn 是一个错误处理示例:

http://mocklab.io/product/1/
{
  "success": true,
  "metadata": {
    "sku": "2",
    "name": "Huawei P20 Pro",
    "max_saving_percentage": 30,
    "price": 13996,
    "special_price": 7990,
    "brand": "Huawei",
    "rating": {
      "average": 4,
      "ratings_total": 265
    },

但在我的情况下,产品“3”给我错误 json : http:mocklab.io/product/3/

{
  "success": false,
  "messages": {
    "error": {
      "reason": "PRODUCT_NOT_FOUND",
      "message": "Product not found!"
    }
  }
}

pojos 已经用 jsonschema2pojo 完成了,所以问题是如果我单击 recyclerview 中的第 3 行,我的应用程序崩溃,因为我得到空对象引用,但我想要的是处理他们提出的错误: HTTP 200 - Success false ,抱歉,如果我没有以最好的方式解释自己,谢谢! 调用:

    GetPhoneDataService service = RetrofitInstance.getRetrofitInstance().create(GetPhoneDataService.class);

        Call<APIReponse> call = service.getAllPhones(1);

        call.enqueue(new Callback<APIReponse>() {
            @Override
            public void onResponse(Call<APIReponse> call, Response<APIReponse> response) {
                if (response.isSuccessful() && response.body() != null) {
                    for (Result result : response.body().getMdata().getResults()) {
                        phoneList.add(result);

                    }
                    adapter.setOnClickListener(new PhonesAdapter.OnItemClickListener() {
                        @Override
                        public void onItemClick(int position) {
                            String sku = phoneList.get(position).getSku();

                            Intent intent = new Intent(MainActivity.this, DetailsActivity.class);
                            intent.putExtra("sku", sku);
                            startActivity(intent);
                        }
                    });
                    adapter.notifyDataSetChanged();
                } else {
                    try {
                        String error = response.errorBody().string();

                        if (error != null) {
                            Log.e("Error : ", error);
                        }
                        //show error to the user

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

【问题讨论】:

    标签: android json retrofit


    【解决方案1】:

    在 Retrofit 中,您可以像这样处理错误响应。内部onResponse 回调:

                       if (response.isSuccessful()
                        && response.body() != null) {
    
                   //Call was successful and body has data
                } else {
                        try {
                            String error = response.errorBody().string();
    
                            if(error != null)
                            //show error to the user
    
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                }
    

    但是如果你的错误在这里抛出:

     public void onItemClick(int position) {
                String sku = phonesList.get(position).getSku();
                Log.e("ffff", "----- " + sku);
    
                Intent intent = new Intent(MainActivity.this,DetailsActivity.class);
                intent.putExtra("sku", sku);
                startActivity(intent);
    
            }
    

    那么您会遇到无法很好地设计代码的问题。当您调用 generatePhonesList 方法时,我不知道您的代码的上下文更准确的上下文,但是,如果您需要多次调用它,那么请考虑不要在该方法中设置 adapterrecyclerview。为此,您有一个叫做:notifyDataSetChanged()

    【讨论】:

    • 谢谢,我编辑了recyclerview,如果想看,我的问题是,产品编号3的JSON不同,所以我的应用程序崩溃了
    猜你喜欢
    • 2014-02-11
    • 2014-10-02
    • 2017-01-01
    • 2016-03-03
    • 2015-07-30
    • 2017-05-23
    • 2020-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多