使用Rxjava2和Retrofit2的自定义DefaultObserver

import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import com.jakewharton.retrofit2.adapter.rxjava2.HttpException;
import com.zhpan.idea.net.common.BasicResponse;
import com.zhpan.idea.net.exception.NoDataExceptionException;
import com.zhpan.idea.net.exception.ServerResponseException;
import com.zhpan.idea.utils.ToastUtils;

import org.json.JSONException;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.ConnectException;
import java.net.UnknownHostException;
import java.text.ParseException;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.ResponseBody;


/**
 *
 */
public abstract class DefaultObserver implements Observer {
    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public void onNext(T response) {
        onSuccess(response);
        onFinish();
    }

    @Override
    public void onError(Throwable e) {
        if (e instanceof HttpException) { // HTTP错误
            HttpException httpException = (HttpException) e;
            ResponseBody errorBody = httpException.response().errorBody();
            // 解析服务端错误( status!=200的情况 )
            if (null != errorBody) {
                String body = "";
                try {
                    body = errorBody.string();
                } catch (IOException ioe) {
                    onFail(ioe.toString());
                }
                try {
                    BasicResponse r = new Gson().fromJson(body, BasicResponse.class);
                    if (null == r) {
                        onFail("null");
                    } else {
                        onFail(r.getMsg());
                    }
                } catch (Exception ex) {
                    onException(ExceptionReason.PARSE_ERROR, ex.toString() + "\n" + body);
                }
            } else {
                onFail("errorBody is null");
            }
        } else if (e instanceof ConnectException || e instanceof UnknownHostException) {   //   连接错误
            onException(ExceptionReason.CONNECT_ERROR, e.getMessage());
        } else if (e instanceof InterruptedIOException) {   //  连接超时
            onException(ExceptionReason.CONNECT_TIMEOUT, e.getMessage());
        } else if (e instanceof JsonParseException || e instanceof JSONException || e instanceof ParseException) {   //  解析错误
            onException(ExceptionReason.PARSE_ERROR, e.toString());
        } else if (e instanceof ServerResponseException) { // 业务错误, 服务端返回的错误
            onFail(e.getMessage());
        } else if (e instanceof NoDataExceptionException) { // 业务正确, 没有获取到数据
            onFail(e.getMessage());
            return;
        } else {
            onException(ExceptionReason.UNKNOWN_ERROR, e.getMessage());
        }
        onFinish();
    }

    @Override
    public void onComplete() {
    }

    /**
     * 请求成功
     *
     * @param response 服务器返回的数据
     */
    abstract public void onSuccess(T response);

    public void onFinish() {
    }

    /**
     * 服务器返回数据,但响应码不为200
     */
    public void onFail(String msg) {
        ToastUtils.show(msg, Toast.LENGTH_LONG);
    }

    /**
     * 请求异常
     *
     * @param reason
     */
    public void onException(ExceptionReason reason, String msg) {
        switch (reason) {
            case CONNECT_ERROR:
                ToastUtils.showLong(ToastUtils.getStr(R.string.connect_error) + "\n" + msg);
                break;
            case CONNECT_TIMEOUT:
                ToastUtils.showLong(ToastUtils.getStr(R.string.connect_timeout) + "\n" + msg);
                break;
            case BAD_NETWORK:
                ToastUtils.showLong(ToastUtils.getStr(R.string.bad_network) + "\n" + msg);
                break;
            case PARSE_ERROR:
                ToastUtils.showLong(ToastUtils.getStr(R.string.parse_error) + "\n" + msg);
                break;
            case UNKNOWN_ERROR:
            default:
                ToastUtils.showLong(ToastUtils.getStr(R.string.unknown_error) + "\n" + msg);
                break;
        }
    }

    /**
     * 请求网络失败原因
     */
    public enum ExceptionReason {
        /**
         * 解析数据失败
         */
        PARSE_ERROR,
        /**
         * 网络问题
         */
        BAD_NETWORK,
        /**
         * 连接错误
         */
        CONNECT_ERROR,
        /**
         * 连接超时
         */
        CONNECT_TIMEOUT,
        /**
         * 未知错误
         */
        UNKNOWN_ERROR,
    }
}

适合ABP的BasicResponse


package com.zhpan.idea.net.common;

/**
 *
 */
public class BasicResponse {

    public T result;
    private boolean success;
    private ResultError error;
    private String targetUrl;
    private boolean unAuthorizedRequest;
    private boolean __abp;

    public String getMsg() {
        if (null == error) {
            return "";
        } else if (null != error.details) {
            if (null != error.validationErrors) {
                return error.message + "\n" + error.details + "\n" + error.validationErrors;
            } else {
                return error.message + "\n" + error.details;
            }
        } else {
            return error.message;
        }
    }

    public T getResult() {
        return result;
    }

    public boolean isSuccess() {
        return success;
    }

    public class ResultError {
        public String code;
        public String message;
        public String details;
        public Object validationErrors;
    }
}

你可能感兴趣的:(使用Rxjava2和Retrofit2的自定义DefaultObserver)