com.payu.sdk.api.handler.ApiErrorHandler Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of api-client Show documentation
Show all versions of api-client Show documentation
A fresh implementation of the PayU API Client for Android
The newest version!
package com.payu.sdk.api.handler;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.payu.sdk.api.exceptions.AuthenticationException;
import com.payu.sdk.api.exceptions.HttpException;
import com.payu.sdk.api.exceptions.NetworkException;
import com.payu.sdk.api.exceptions.PayUException;
import com.payu.sdk.api.exceptions.SDKException;
import java.io.IOException;
import okio.BufferedSource;
import okio.Okio;
import retrofit.ErrorHandler;
import retrofit.RetrofitError;
import retrofit.client.Response;
import static com.payu.sdk.base.Preconditions.isNull;
public class ApiErrorHandler implements ErrorHandler {
private final static int UNAUTHORIZED_CODE = 401;
@Override public Throwable handleError(RetrofitError cause) {
Response response = cause.getResponse();
switch (cause.getKind()) {
case NETWORK:
return new NetworkException(cause.getMessage(), cause);
case CONVERSION:
return new PayUException(SDKException.ErrorCode.CONVERSION_ERROR, cause.getMessage());
case HTTP:
if (response != null) {
String message = validateMessage(cause);
switch (response.getStatus()) {
case UNAUTHORIZED_CODE:
return new AuthenticationException(message, cause);
default:
return new HttpException(message, cause);
}
} else {
return new HttpException(cause.getMessage(), cause);
}
case UNEXPECTED:
return cause;
}
return cause;
}
private String validateMessage(RetrofitError cause) {
String apiError = obtainApiError(cause.getResponse());
return (isNull(apiError)) ? cause.getMessage() : apiError;
}
private String obtainApiError(Response response) {
if (isNull(response)) {
return null;
}
try {
BufferedSource source = Okio.buffer(Okio.source(response.getBody().in()));
return source.readUtf8();
} catch (IOException | JsonSyntaxException exception) {
return processError.toJson(processError.getUnexpectedError());
}
}
public static class ApiError {
public String type;
public String description;
}
public static class processError {
public static ApiError fromJson(String apiErrorResponse) {
return new Gson().fromJson(apiErrorResponse, ApiError.class);
}
public static String toJson(ApiError apiError) {
return new Gson().toJson(apiError, ApiError.class);
}
public static ApiError getUnexpectedError() {
ApiError apiError = new ApiError();
apiError.description = "Unexpected Error";
apiError.type = "UNEXPECTED";
return apiError;
}
}
}