Skip to content

Instantly share code, notes, and snippets.

@behdad222
Last active February 1, 2019 08:09
Show Gist options
  • Save behdad222/9378f7aff8acf3c19307e784b374b865 to your computer and use it in GitHub Desktop.
Save behdad222/9378f7aff8acf3c19307e784b374b865 to your computer and use it in GitHub Desktop.
public abstract class ResponseWithErrorHandling<R, E> implements Callback<ResponseBody> {
private Type responseType;
private Type errorType;
public abstract void onResponseRequest(Call<ResponseBody> call, R response);
public abstract void onErrorRequest(Call<ResponseBody> call, E error);
public abstract void onFailureRequest(Call<ResponseBody> call, Throwable error);
protected ResponseWithErrorHandling() {
this.responseType = ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
this.errorType = ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1];
}
@Override
public final void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) {
try {
if (response.isSuccessful()) {
R mResponse = new Gson().fromJson(response.body().string(), responseType);
onResponseRequest(call, mResponse);
} else {
E mError = new Gson().fromJson(response.errorBody().string(), errorType);
onErrorRequest(call, mError);
}
} catch (Exception e) {
e.printStackTrace();
onFailureRequest(call, e);
}
}
@Override
public final void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable t) {
onFailureRequest(call, t);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment