RXJava2+Retrofit2+MVP+RXLifecycle+EventBus+...之你可能需要的那些套路(二)

本文所涉及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由于篇幅问题,后续诸多套路,请听下回分解。

附上源代码地址:https://github.com/LegendaryMystic/HYMVP

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 193,968评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,682评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,254评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,074评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,964评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,055评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,484评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,170评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,433评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,512评论 2 308
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,296评论 1 325
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,184评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,545评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,150评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,437评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,630评论 2 335

推荐阅读更多精彩内容

  • 我从去年开始使用 RxJava ,到现在一年多了。今年加入了 Flipboard 后,看到 Flipboard 的...
    Jason_andy阅读 5,435评论 7 62
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,490评论 18 139
  • 我就是那个爱梦想,爱追求,爱上进,爱一切进步的正能量的所谓上进的人。我爱一切有上进心的人和事,偏偏这个时候...
    蜗蜗牛1阅读 158评论 0 0
  • 文/粥小唯 下班溜进家门,发现七大姑八大姨还有一个我不认识的阿姨整整齐齐围的坐在沙发边,貌似在商量着什么,看到我回...
    妖精的小尾巴阅读 453评论 2 6
  • 文/小颐妈 刚过完年,我的一个下属跟我说,“姐,听说小静要离职”。 “哦,知道了,那按工作安排,你继续做好你的工作...
    小颐妈阅读 206评论 0 0