Guest User

Untitled

a guest
Dec 15th, 2017
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. public abstract class ResponseWithErrorHandling<R, E> implements Callback<ResponseBody> {
  2. private Type responseType;
  3. private Type errorType;
  4.  
  5. public abstract void onResponseRequest(Call<ResponseBody> call, R response);
  6.  
  7. public abstract void onErrorRequest(Call<ResponseBody> call, E error);
  8.  
  9. public abstract void onFailureRequest(Call<ResponseBody> call, Throwable error);
  10.  
  11. protected ResponseWithErrorHandling() {
  12. this.responseType = ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
  13. this.errorType = ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1];
  14. }
  15.  
  16. @Override
  17. public final void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) {
  18.  
  19. try {
  20.  
  21. if (response.isSuccessful()) {
  22. R mResponse = new Gson().fromJson(response.body().string(), responseType);
  23. onResponseRequest(call, mResponse);
  24.  
  25. } else {
  26. E mError = new Gson().fromJson(response.errorBody().string(), errorType);
  27. onErrorRequest(call, mError);
  28.  
  29. }
  30.  
  31. } catch (Exception e) {
  32. e.printStackTrace();
  33. onFailureRequest(call, e);
  34. }
  35. }
  36.  
  37. @Override
  38. public final void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable t) {
  39. onFailureRequest(call, t);
  40. }
  41. }
Add Comment
Please, Sign In to add comment