How do I get Response body when there is an error when using Retrofit 2.0 Observables

前端 未结 3 1732
眼角桃花
眼角桃花 2021-01-31 16:13

I am using Retrofit 2.0 to make api calls that return Observables. It all works good when the call went through fine and the response is as expected. Now let\'s say we have an e

3条回答
  •  粉色の甜心
    2021-01-31 16:25

    You can add this code block to display the error message.

    @Override
    public void onFailure(Throwable t) {
    
     if (t instanceof HttpException) {
            ResponseBody body = ((HttpException) t).response().errorBody();
            Gson gson = new Gson();
            TypeAdapter adapter = gson.getAdapter
                    (ErrorParser
                            .class);
            try {
                ErrorParser errorParser =
                        adapter.fromJson(body.string());
    
                Logger.i(TAG, "Error:" + errorParser.getError());
    
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

提交回复
热议问题