Issue
Just tied Retrofit and it is great. Don't want to invent something new so is there any way to handle all possible errors in failure()
.
Or the only way is to check all statuses and for example show Dialogs?
@Override
public void failure(RetrofitError error) {
}
Solution
If you build your retrofitadapter you will see that it has the option of including a custom error handler. The method to use is .setErrorHandler(errorHandler);
So what you can do is create the following class and attach it to your retrofit builder in the way described above :
public class ErrorUtil implements ErrorHandler {
public ErrorUtil() {
}
public Throwable handleError(RetrofitError cause) {
String errorDescription = null;
Log.e("NON FATAL ERROR: ", cause.getLocalizedMessage());
if (cause.getKind().equals(RetrofitError.Kind.NETWORK)) {
if (!isNetworkAvailable()) {
errorDescription = ErrorConstants.ERROR_CONNECTION_OFFLINE;
} else if (cause.getMessage().contains("Unable to resolve host") || cause.getMessage().contains("Invalid sequence") || cause.getMessage().contains("Illegal character") || cause.getMessage().contains("was not verified")) {
errorDescription = ErrorConstants.ERROR_UNABLE_TO_RESOLVE_HOST;
} else if (cause.getLocalizedMessage().contains("timeout") || cause.getLocalizedMessage().contains("timed out") || cause.getLocalizedMessage().contains("failed to connect")) {
errorDescription = ErrorConstants.ERROR_CONNECTION_TIMEOUT;
} else if (cause.getLocalizedMessage().equals("Connection closed by peer") || cause.getLocalizedMessage().equals("host == null") || cause.getLocalizedMessage().contains("CertPathValidatorException")) {
errorDescription = ErrorConstants.ERROR_UNABLE_TO_RESOLVE_HOST;
} else {
errorDescription = ErrorConstants.ERROR_NETWORK;
}
} else if (cause.getKind().equals(RetrofitError.Kind.CONVERSION)) {
errorDescription = ErrorConstants.ERROR_JSON_RESPONSE_CONVERSION;
} else if (cause.getResponse() == null) {
errorDescription = ErrorConstants.ERROR_NO_RESPONSE;
} else {
errorDescription = ErrorConstants.ERROR_UNKNOWN;
}
Log.d("ERRORUTILReturn", errorDescription);
return new Exception(errorDescription);
}
Sorry for posting a wall of code but this is the solution we used to get a human readable error format out of the retrofit error handler. You can edit this to better match your error set. We also localized the error messages inside the error handler class.
Then just use the following to have a nice readable error format that you can display to the user:
@Override
public void failure(RetrofitError error) {
error.getLocalizedMessage();
}
Answered By - Smashing
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.