Created
June 29, 2016 16:42
-
-
Save alwx/0a220cd85d4b58820c3c49524ac1dc36 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
package example.api; | |
import android.support.annotation.NonNull; | |
import retrofit2.Call; | |
import ru.quiick_commons.api.response.ErrorResponse; | |
import ru.quiick_commons.logger.Logger; | |
import okhttp3.ResponseBody; | |
import java.io.IOException; | |
import java.lang.annotation.Annotation; | |
import retrofit2.Callback; | |
import retrofit2.Converter; | |
import retrofit2.Response; | |
import retrofit2.Retrofit; | |
/** | |
* @author alwx (http://alwx.me) | |
* @version 1.0 | |
*/ | |
public abstract class APICallback<T> implements Callback<T> { | |
public abstract void onSuccess(T response); | |
public abstract void onError(@NonNull ErrorResponse errorResponse); | |
public abstract void onNetworkError(Throwable t); | |
@Override | |
public void onResponse(Call<T> call, Response<T> response) { | |
if (response.isSuccessful()) { | |
onSuccess(response.body()); | |
} else if (response.code() == 403 || response.code() == 500) { | |
onError(new ErrorResponse(response.code(), null)); | |
} else { | |
Retrofit retrofit = API.getRetrofit(); | |
if (retrofit != null) { | |
Converter<ResponseBody, ErrorResponse> errorConverter = | |
retrofit.responseBodyConverter(ErrorResponse.class, new Annotation[0]); | |
try { | |
ErrorResponse errorResponse = errorConverter.convert(response.errorBody()); | |
if (errorResponse.getError() != null) { | |
onError(errorResponse); | |
} else { | |
Logger.error("Empty error: " + response.errorBody().string()); | |
} | |
} catch (IOException e) { | |
Logger.error("APICallback exception: " + e); | |
} | |
} | |
} | |
} | |
@Override | |
public void onFailure(Call<T> call, Throwable t) { | |
onNetworkError(t); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment