Retrofit + RxJava exception processing network requests

This article is based Retrofit + RxJava do some neat package. The main explanation for the error once the package requested information network to help us reasonably be displayed in the UI interface based on the status returned. Combined with the article to configure the Retrofit of. RxJava + Retrofit to network requests for use of the package, including a cache processing, exception processing, and other requests, a request to use most network conditions, i.e., pull-use. You can go to the bottom of the address to download the code.

This article is based on RxJava 2.0 and Retrofit 2.1 analysis.
The following lists specific dependency added.

 //引入okhttp
    compile 'com.squareup.okhttp3:okhttp:3.5.0'
    //引入retrofit
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    //引入rxjava
    compile 'io.reactivex.rxjava2:rxjava:2.0.4'
    //引入Log拦截器,方便DEBUG模式输出log信息
    compile 'com.squareup.okhttp3:logging-interceptor:3.5.0'
    //引入rxjava适配器,方便rxjava与retrofit的结合
    compile 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'
    //引入json转换器,方便将返回的数据转换为json格式
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
    //引入rxandroid
    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'

The need for exception handling

The following these errors are in a network request via common. We pop-up message can notify the user of an abnormality and specific loading through the corresponding UI interface Toast. In addition, through specific exception information to help us in time of investigation projects in the BUG.

[Picture upload failed ... (image-417991-1559564709706)]

So the question becomes, how do we determine the type of exception?

This is from the server to return data format talking about.

We generally request the return is like this

{
   "code":"200",
   "message":"Return Successd!",
   "data":{
         "name":"张三"
          "age":3
   }
}

The server returns the data is probably more commonly known as the agreed format. Meaning Possible specific code representation of the code is not the same, this can communicate with server-side personnel, flexible change.
The basic configuration is no longer about Retrofit told, I can see another article . Here explain in detail how to use the packaging and data server returns error information processing RxJava.

Packaging return data type judgment and abnormality

Package return data
returned to said data server code we want to make some determination, not code 200 (assuming network 200 indicates that the request is successful) will throw an exception. So we create a BaseResponse class, corresponding to the above data structure.

public class BaseResponse<T> {

    private int code;
    private String msg;
    private T data;
//该方法假设服务器返回200表示成功返回结果,其他数字表示异常
    public boolean isOk() {
        return code ==200;
    }
//省略getter,setter方法
}

This is regarded as a base class for all entities, data can be any data type.

Then returns a result to be pretreated, a new ExceptionHandle. Pretreatment is nothing more than is true when it is judged whether or not, when the normal processing is true, otherwise an exception is thrown so ExceptionHandle further processing, which determines an abnormality of the abnormality in accordance with the return data BaseResponse ISOK () method. Let's skip ahead logic, to understand how to determine what is abnormal?
Analyzing exception type

public class ExceptionHandle {
    //该方法用来判断异常类型 并将异常类型封装在ResponeThrowable返回
    public static ResponeThrowable handleException(Throwable e) {
          if (e instanceof HttpException) {
                  HttpException httpException = (HttpException) e;
                  ex = new ResponeThrowable(e, ERROR.HTTP_ERROR);
                  ex.message = "网络错误";
                  return ex;
          }
         ...................
         ...................其他类型异常判断
         ...................
     }
}

A detailed look at the source code, will be posted the following address.
By ExceptionHandle.handleException (Throwable e) to return an exception, the exception type and carries specific information.

Now we already know how to determine whether and how to determine produce more than exception type. Next you need to solve is how to pass the exception to the Observer onError (Throwable e) to handle exceptions.

Abnormal transfer

Abnormal transfer process in carrying out the first step we must first determine whether the server returns the data is abnormal, if the data is not abnormal data is returned, if an exception is thrown. This time includes a data conversion process to convert BaseResponse i.e. objects into an object data type, it is necessary to map () operator.

(Observable<T>) upstream.map(new HandleFuc<T>())

HandleFuc which implements Function<BaseResponse<T>, T>the interface

 public static class HandleFuc<T> implements Function<BaseResponse<T>, T> {
        @Override
        public T apply(BaseResponse<T> response) throws Exception {
            //response中code码不为200 出现错误
            if (!response.isOk())
                //抛出异常,把状态码及状态描述信息传入
                throw new RuntimeException(response.getCode() + "" + response.getMsg() != null ? response.getMsg() : "");
            return response.getData();
        }
    }

If an exception does not appear it will not take the second step. If an exception occurs, the second step is required, i.e., an abnormal state is determined, then ExceptionHandle.handleException (Throwable e) returning the onError abnormal afferent () processing.

Focus here: Called when an exception should be terminated onNext () method and call onError () method. If we do not continue to process, only through the above steps, although it will call onError () method, but there is no abnormality judgment, and no cancellation onNext () method. Is there a good way, that is, you can cancel onNext () method, which can achieve abnormality determination in the implementation, and calls onError () method?

Such a powerful RxJava naturally this way, and onErrorResumeNext()we will be able to fulfill the requirement. For onErrorResumeNext(), it can be simply understood as follows: When an error occurs, be replaced by another Observable Observable current and continue to transmit data.

onErrorResumeNext()The parameters can be passed in a Function interface. In this way, we can generate a Function Observable, the abnormality determination execution logic Observable, and calls the onError () method.
Specific achieve the following:

(Observable<T>) upstream.map(new HandleFuc<T>()).onErrorResumeNext(new HttpResponseFunc<T>());

public static class HttpResponseFunc<T> implements Function<Throwable, Observable<T>> {
        @Override
        public Observable<T> apply(Throwable throwable) throws Exception {
            return Observable.error(ExceptionHandle.handleException(throwable));
        }
    }

At this point, we realized the logic abnormality determination and delivery. So that we can extract specific information on the onError abnormal state () method, the corresponding processing.
Process is about: map () data type conversion, and detecting abnormality. If OK, return data type of data. If not normal, onErrorResumeNext () determines the type of exception and the exception pass
below show a simple renderings:

Close the above network. When initiating a network request, no network exception is thrown, then detect specific abnormal, Toast prompts exception type, the user will know what went wrong.

In conjunction with the article to configure the Retrofit of. RxJava + Retrofit to network requests for use of the package, including a cache processing, exception processing, and other requests, a request to use most network conditions, i.e., pull-use. You can go to the following address to download the code.
Code address

It is engaged in the development of the Android engineers for seven years, a lot of people ask me privately, 2019 Android how advanced the science, there is no method?

Yes, at the beginning I spent more than a month to sort out learning materials, hoping to help those who want to enhance the advanced Android development, but do not know how advanced learning friends. [ Including advanced UI, performance optimization, Architect courses, NDK, Kotlin, hybrid development (ReactNative + Weex), Flutter and other technical information architecture ], hoping to help review your pre-interview and find a good job, but also save in time they search for information online to learn.

Obtaining: Add Android architecture exchange QQ group chat: 513 088 520, into the group that is to receive the information! ! !

Click on the link to join a group chat Android mobile architecture [total population]: join a group chat

Sourcebook

Guess you like

Origin blog.csdn.net/weixin_43351655/article/details/90758440