Last active
February 1, 2019 08:09
-
-
Save behdad222/9378f7aff8acf3c19307e784b374b865 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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