Created
March 28, 2016 12:40
-
-
Save halysongoncalves/8acf304408393ae17ed3 to your computer and use it in GitHub Desktop.
CallbackRequest Retrofit 2.0
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
import android.util.Log; | |
import java.io.IOException; | |
import retrofit2.Call; | |
import retrofit2.Callback; | |
import retrofit2.Response; | |
/** | |
* Created by halysongoncalves on 22/12/15. | |
*/ | |
public abstract class CallbackRequest<T> implements Callback<T> { | |
private static final String TAG = CallbackRequest.class.getSimpleName(); | |
@Override | |
public void onResponse(Call<T> call, Response<T> response) { | |
try { | |
switch (response.code()) { | |
case Kind.HTTP_200: | |
http2xx(Kind.HTTP_200, response); | |
break; | |
case Kind.HTTP_201: | |
http2xx(Kind.HTTP_201, response); | |
break; | |
case Kind.HTTP_204: | |
http2xx(Kind.HTTP_200, response); | |
break; | |
case Kind.HTTP_400: | |
http400(response.errorBody().string(), Kind.HTTP_400); | |
break; | |
case Kind.HTTP_401: | |
http401(response.errorBody().string(), Kind.HTTP_401); | |
break; | |
case Kind.HTTP_403: | |
unexpectedError(); | |
break; | |
default: | |
unexpectedError(); | |
break; | |
} | |
} catch (IOException ioExceotion) { | |
Log.e(TAG, "Error retrieving body", ioExceotion); | |
} | |
} | |
@Override | |
public void onFailure(Call<T> call, Throwable throwable) { | |
if (throwable instanceof IOException) { | |
networkError(); | |
return; | |
} | |
unexpectedError(); | |
} | |
protected abstract void http2xx(int status, Response<T> response); | |
protected abstract void http400(String error, int status); | |
protected abstract void http401(String error, int status); | |
protected abstract void networkError(); | |
protected abstract void unexpectedError(); | |
interface Kind { | |
/** | |
* HTTP status code 200 was received from the server | |
*/ | |
int HTTP_200 = 200; | |
/** | |
* HTTP status code 201 was received from the server | |
*/ | |
int HTTP_201 = 201; | |
/** | |
* HTTP status code 204 was received from the server | |
*/ | |
int HTTP_204 = 204; | |
/** | |
* HTTP status code 400 was received from the server | |
*/ | |
int HTTP_400 = 400; | |
/** | |
* HTTP status code 401 was received from the server. | |
*/ | |
int HTTP_401 = 401; | |
/** | |
* HTTP status code 403 was received from the server. | |
*/ | |
int HTTP_403 = 403; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment