Skip to content

Instantly share code, notes, and snippets.

@syllabix
Last active May 17, 2017 02:54
Show Gist options
  • Save syllabix/d2aa2fd38c60a6967180b0397d233fa6 to your computer and use it in GitHub Desktop.
Save syllabix/d2aa2fd38c60a6967180b0397d233fa6 to your computer and use it in GitHub Desktop.
A very simple opinionated subclass of a Retrofit.Callback
package com.example.gist.ResponseHandler
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.IOException;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public abstract class ResponseHandler<T> implements Callback<T> {
@Override
public void onResponse(Call<T> call, Response<T> response) {
if(response.isSuccessful()) {
onSuccess(call, response);
} else {
Gson gson = new GsonBuilder().create();
try {
ErrorResponse error = gson.fromJson(response.errorBody().string(), ErrorResponse.class);
onError(error.getMessage());
} catch (IOException e) {
onError("An unexpected error occurred");
}
}
}
@Override
public void onFailure(Call<T> call, Throwable t) {
String msg = t.getMessage();
onError(msg);
}
public abstract void onSuccess(Call<T> call, Response<T> response);
public abstract void onError(String message);
public class ErrorResponse {
private String message;
public String getMessage() {
return message;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment