Created
March 13, 2018 13:52
-
-
Save ntakouris/b5affe851c8680c2105d64fb59bac350 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 class ApiResponseCallbackAdapter<T> implements Callback<ApiResponse<T>> { | |
Callback<T> callback; | |
public ApiResponseCallbackAdapter(Callback<T> callback) { | |
this.callback = callback; | |
} | |
@Override | |
public void onResponse(Call<ApiResponse<T>> call, Response<ApiResponse<T>> response) { | |
callback.onEverytime(); | |
if (response == null) { | |
callback.onFailure(false); | |
return; | |
} | |
int responseCode = response.code(); | |
if (responseCode >= 500) { | |
callback.onServerError(response); | |
return; | |
} | |
if (responseCode == 401) { | |
callback.onUnAuthorized(); | |
return; | |
} | |
if (responseCode == 403) { | |
callback.onForbidden(); | |
return; | |
} | |
if (responseCode >= 400) { | |
ApiResponse<T> responseBody = null; | |
try { | |
responseBody = new Gson().fromJson(response.errorBody().string(), ApiResponse.class); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} finally { | |
if (responseBody == null) { | |
callback.onFailure(false); | |
return; | |
} | |
callback.onBadRequest(responseBody.getErrors()); | |
return; | |
} | |
} | |
callback.onSuccessfulResponse(response.body()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment