本文所涉及DEMO已上传至https://github.com/LegendaryMystic/HYMVP
本人小白一个,文章废话较多,如果你觉得talk is cheap,喜欢直接 read the fuck source code,可跳过直接前往
码字不易,如果代码能够帮到你,望不吝给个鼓励的star,感谢!
本文承接上文RXJava2+Retrofit2+MVP+RXLifecycle+EventBus+...之你可能需要的那些套路(一),我们接着讲RxJava+Retrofit结合MVP架构模式在实际项目中你可能需要的一些基本的套路。
套路四:异常、错误或解密统一处理
刚开始使用RxJava进行网络请求时,我们常用onNext
作为请求响应的回调,onError
异常回调
public interface Observer<T> {
/**
* Provides the Observer with the means of cancelling (disposing) the
* connection (channel) with the Observable in both
* synchronous (from within {@link #onNext(Object)}) and asynchronous manner.
* @param d the Disposable instance whose {@link Disposable#dispose()} can
* be called anytime to cancel the connection
* @since 2.0
*/
void onSubscribe(@NonNull Disposable d);
/**
* Provides the Observer with a new item to observe.
* <p>
* The {@link Observable} may call this method 0 or more times.
* <p>
* The {@code Observable} will not call this method again after it calls either {@link #onComplete} or
* {@link #onError}.
*
* @param t
* the item emitted by the Observable
*/
void onNext(@NonNull T t);
/**
* Notifies the Observer that the {@link Observable} has experienced an error condition.
* <p>
* If the {@link Observable} calls this method, it will not thereafter call {@link #onNext} or
* {@link #onComplete}.
*
* @param e
* the exception encountered by the Observable
*/
void onError(@NonNull Throwable e);
/**
* Notifies the Observer that the {@link Observable} has finished sending push-based notifications.
* <p>
* The {@link Observable} will not call this method if it calls {@link #onError}.
*/
void onComplete();
}
然而,值得一提的是,这里onError
回调给我们的是一个Throwable
,面对这个Throwable
对象,或许我们只能log它的message,而且可能反复的写。。这个时候就需要封装了。
我们希望,像大多数网络请求框架一样,简单的两个回调函数:
/**
* 请求成功
*
* @param response 服务器返回的数据
*/
public abstract void onSuccess(T response);
/**
* 服务器返回数据,但code不在约定成功范围内
*
* @param msg 服务器返回的数据
*/
public abstract void onFailure(String msg);
请求成功,返回给我们需要的数据展示到UI界面,请求失败(比如参数错误等请求逻辑错误),返回给用户一条失败提示,而对于请求异常(如网络异常,数据解析失败..等请求异常),我们只需在内部统一log记录便于debug。
一般的,服务器返回给我们的数据可能是:
{
"code": 200,
"msg": "成功",
"data": {}
}
对应实体类:
/* http响应参数实体类
* 通过Gson解析属性名称需要与服务器返回字段对应,或者使用注解@SerializedName
* /
public class BaseResponse<T>{
private int code;
private String msg;
private T data;
/**
* 是否成功(这里约定200)
*
* @return
*/
public boolean isSuccess() {
return code == 200 ? true : false;
}
我们与后台约定状态码符合约定规则时为请求成功,正常情况下如果某一个http请求没有发生异常,或者网络错误,就会走onNext回调,现在我们要让code
不等于200的响应进入失败回调,
自定义一个ResultException
用于捕获服务器约定的错误类型
public class ResultException extends RuntimeException{
private int code;
private String message;
public ResultException(int code, String message){
this.code = code;
this.message = message;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
自定义一个Gson响应体转换类MyGsonResponseBodyConverter
public class MyGsonResponseBodyConverter<T> implements Converter<ResponseBody,T> {
private final Gson gson;
private final Type type;
public MyGsonResponseBodyConverter(Gson gson, Type type){
this.gson = gson;
this.type = type;
}
@Override
public T convert(@NonNull ResponseBody value) throws IOException {
String response = value.string();
BaseResponse<T> result = gson.fromJson(response, BaseResponse.class);
if (result.isSuccess()){
//对于请求数据加密的 可以在这里做解密操作
return gson.fromJson(jsonStr,type);
}else {
//抛一个自定义ResultException 传入失败时候的状态码,和信息
throw new ResultException(result.getCode(),result.getMsg());
}
}
}
拷贝一份GsonConverterFactory
,将GsonResponseBodyConverter
替换为前面我们自定义的MyGsonResponseBodyConverter
/**
* A {@linkplain Converter.Factory converter} which uses Gson for JSON.
* <p>
* Because Gson is so flexible in the types it supports, this converter assumes that it can handle
* all types. If you are mixing JSON serialization with something else (such as protocol buffers),
* you must {@linkplain Retrofit.Builder#addConverterFactory(Converter.Factory) add this instance}
* last to allow the other converters a chance to see their types.
*/
public final class MyGsonConverterFactory extends Converter.Factory {
/**
* Create an instance using a default {@link Gson} instance for conversion. Encoding to JSON and
* decoding from JSON (when no charset is specified by a header) will use UTF-8.
*/
public static MyGsonConverterFactory create() {
return create(new Gson());
}
/**
* Create an instance using {@code gson} for conversion. Encoding to JSON and
* decoding from JSON (when no charset is specified by a header) will use UTF-8.
*/
@SuppressWarnings("ConstantConditions") // Guarding public API nullability.
public static MyGsonConverterFactory create(Gson gson) {
if (gson == null) throw new NullPointerException("gson == null");
return new MyGsonConverterFactory(gson);
}
private final Gson gson;
private MyGsonConverterFactory(Gson gson) {
this.gson = gson;
}
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
Retrofit retrofit) {
//TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
//return new GsonResponseBodyConverter<>(gson, adapter);
//返回我们自定义的Gson响应体变换器
return new MyGsonResponseBodyConverter<>(gson, type);
}
@Override
public Converter<?, RequestBody> requestBodyConverter(Type type,
Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
return new GsonRequestBodyConverter<>(gson, adapter);
}
}
然后在构建Retrofit
时注册这个自定义的MyResponseConverterFactory
retrofit = new Retrofit.Builder()
.baseUrl(ApiService.BASE_URL)
.client(client)
//然后将下面的GsonConverterFactory.create()替换成我们自定义的MyResponseConverterFactory.create()
.addConverterFactory(MyResponseConverterFactory.create())
// .addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
到此为止与后台服务器约定的错误类型,抛出到onError
回调中就完成了,举一反三,对于请求返回Json数据加密的,以及返回Json数据 格式不固定的 比如:
{
"result":"结果代号,0表示成功",
"msg":"成功返回时是消息数据列表,失败时是异常消息文本"
}
这里msg究竟应该定义为String,还是一个List呢?
等等都可以在Gson响应体转换类GsonResponseBodyConverter中做相应的解密或相关判断转换处理,这里我就不一一列举了。
对于请求异常,为了方便调试,自定义一个ApiException
,对Throwable
做具体的处理
public class ApiException extends Exception {
//对应HTTP的状态码
private static final int UNAUTHORIZED = 401;
private static final int FORBIDDEN = 403;
private static final int NOT_FOUND = 404;
private static final int REQUEST_TIMEOUT = 408;
private static final int INTERNAL_SERVER_ERROR = 500;
private static final int BAD_GATEWAY = 502;
private static final int SERVICE_UNAVAILABLE = 503;
private static final int GATEWAY_TIMEOUT = 504;
private final int code;
private String message;
public ApiException(Throwable throwable, int code) {
super(throwable);
this.code = code;
this.message = throwable.getMessage();
}
public int getCode() {
return code;
}
@Override
public String getMessage() {
return message;
}
public static ApiException handleException(Throwable e) {
Throwable throwable = e;
//获取最根源的异常
while (throwable.getCause() != null) {
e = throwable;
throwable = throwable.getCause();
}
ApiException ex;
if (e instanceof HttpException) { //HTTP错误
HttpException httpException = (HttpException) e;
ex = new ApiException(e, httpException.code());
switch (httpException.code()) {
case UNAUTHORIZED:
case FORBIDDEN:
//权限错误,需要实现重新登录操作
// onPermissionError(ex);
break;
case NOT_FOUND:
case REQUEST_TIMEOUT:
case GATEWAY_TIMEOUT:
case INTERNAL_SERVER_ERROR:
case BAD_GATEWAY:
case SERVICE_UNAVAILABLE:
default:
ex.message = "默认网络异常"; //均视为网络错误
break;
}
return ex;
} else if (e instanceof SocketTimeoutException) {
ex = new ApiException(e, ERROR.TIMEOUT_ERROR);
ex.message = "网络连接超时,请检查您的网络状态,稍后重试!";
return ex;
} else if (e instanceof ConnectException) {
ex = new ApiException(e, ERROR.TIMEOUT_ERROR);
ex.message = "网络连接异常,请检查您的网络状态,稍后重试!";
return ex;
} else if (e instanceof ConnectTimeoutException) {
ex = new ApiException(e, ERROR.TIMEOUT_ERROR);
ex.message = "网络连接超时,请检查您的网络状态,稍后重试!";
return ex;
} else if (e instanceof UnknownHostException) {
ex = new ApiException(e, ERROR.TIMEOUT_ERROR);
ex.message = "网络连接异常,请检查您的网络状态,稍后重试!";
return ex;
} else if (e instanceof NullPointerException) {
ex = new ApiException(e, ERROR.NULL_POINTER_EXCEPTION);
ex.message = "空指针异常";
return ex;
} else if (e instanceof javax.net.ssl.SSLHandshakeException) {
ex = new ApiException(e, ERROR.SSL_ERROR);
ex.message = "证书验证失败";
return ex;
} else if (e instanceof ClassCastException) {
ex = new ApiException(e, ERROR.CAST_ERROR);
ex.message = "类型转换错误";
return ex;
} else if (e instanceof JsonParseException
|| e instanceof JSONException
// || e instanceof JsonSyntaxException
|| e instanceof JsonSerializer
|| e instanceof NotSerializableException
|| e instanceof ParseException) {
ex = new ApiException(e, ERROR.PARSE_ERROR);
ex.message = "解析错误";
return ex;
} else if (e instanceof IllegalStateException) {
ex = new ApiException(e, ERROR.ILLEGAL_STATE_ERROR);
ex.message = e.getMessage();
return ex;
} else {
ex = new ApiException(e, ERROR.UNKNOWN);
ex.message = "未知错误";
return ex;
}
}
/**
* 约定异常
*/
public static class ERROR {
/**
* 未知错误
*/
public static final int UNKNOWN = 1000;
/**
* 连接超时
*/
public static final int TIMEOUT_ERROR = 1001;
/**
* 空指针错误
*/
public static final int NULL_POINTER_EXCEPTION = 1002;
/**
* 证书出错
*/
public static final int SSL_ERROR = 1003;
/**
* 类转换错误
*/
public static final int CAST_ERROR = 1004;
/**
* 解析错误
*/
public static final int PARSE_ERROR = 1005;
/**
* 非法数据异常
*/
public static final int ILLEGAL_STATE_ERROR = 1006;
}
最后,自定义一个Observer抽象类对请求回调做具体的处理
public abstract class BaseObserver<T> implements Observer<T> {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(T response) {
onSuccess(response);
}
@Override
public void onError(Throwable e) {
//抛出的与服务器约定的错误类型
if (e instanceof ResultException){
onFailure(e.getMessage());
}else {
String error = ApiException.handleException(e).getMessage();
_onError(error);
}
}
@Override
public void onComplete() {
}
/**
* 请求成功
*
* @param response 服务器返回的数据
*/
public abstract void onSuccess(T response);
/**
* 服务器返回数据,但code不在约定成功范围内
*
* @param msg 服务器返回的数据
*/
public abstract void onFailure(String msg);
// public abstract void onError(String errorMsg);
private void _onSuccess(T responce){
}
private void _onFailure(String msg) {
if (TextUtils.isEmpty(msg)) {
// ToastUtils.show(R.string.response_return_error);
} else {
// ToastUtils.show(msg);
}
}
private void _onError(String err ){
Log.e("APIException",err);
}
}
使用的时候在presenter里subscribe自定义的BaseObserver即可
mModel.getSurvey(did)
.compose(RxTransformer.transformWithLoading(mView))
.subscribe(new BaseObserver<Survey>() {
@Override
public void onSuccess(Survey response) {
mView.onGetSurvey(response);
}
@Override
public void onFailure(String msg) {
}
});
废话有点多了,详情请见源代码HYMVP由于篇幅问题,后续诸多套路,请听下回分解。