title: Handle retrofit 2 GSON conversion errors
body: <p>I am using retrofit with GSON and RxJava to carry out network requests. I am trying to figure out how to get the response when the Gson library fails to convert it.</p>
  
  <p>This takes place when an error takes place on the server and the response does not match the class that the Gson library is trying to convert the response to.</p>
  
  <p>A work around would be to create an interceptor and cache the response before we try to convert it. But that's just bad programming as the problem will become unmanageable once we start doing concurrent requests.</p>
  
  <p><strong>the service is defined as follows: The response class contains just a status code and a generic type called data.</strong>    </p>
  
  <pre><code>Retrofit getService() {
       return new Retrofit.Builder()
              .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
              .addConverterFactory(GsonConverterFactory.create())
              .baseUrl(url)
              .client(clientBuilder.build())
              .build();
  }
  public Observable&lt;Response&lt;String&gt;&gt; userLogin(String username, String password) {
  
      return getService().create(Account.class)
              .login(username, password)
              .subscribeOn(Schedulers.newThread())
              .observeOn(AndroidSchedulers.mainThread());
  }
  </code></pre>
  
  <p><strong>Somewhere else in the code we create a request</strong></p>
  
  <pre><code>getService().userLogin(email, password)
          .subscribeOn(Schedulers.newThread())
          .observeOn(AndroidSchedulers.mainThread())
          .subscribe(onSuccess(), onError());
  
  protected Action1&lt;Response&lt;String&gt;&gt; onSuccess(){
  
      return new Action1&lt;Response&lt;String&gt;&gt;() {
          @Override
          public void call(Response&lt;String&gt; response) {
               // Process the response
          }
      };
  }
  protected Action1&lt;Throwable&gt; onError(){
      return new Action1&lt;Throwable&gt;() {
          @Override
          public void call(Throwable throwable) {
  
              if (throwable instanceof HttpException) {
                  ResponseBody body = ((HttpException)  throwable).response().errorBody();
                  // Handle the error
              }
          }
      };
  </code></pre>
  
  <p>The problem occurs when the server returns something other than a string. For example an object or an array. Here the GsonConverterFactory will throw an error that will be caught by the onError method. I am wondering how can I get response.</p>
  
  <p>The throwable that is returned is of type <code>JsonSyntaxException</code> and sadly it does not contain the original response body that the GSON library has tried to convert.</p>