androidネットワークリクエストタイムアウト単純処理(rxjavaベース)

2802 ワード

implementation ‘com.squareup.retrofit2:adapter-rxjava:2.1.0’
public class ExceptionHandle { 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;
public static ResponeThrowable handleException(Throwable e) {
    ResponeThrowable ex;
    if (e instanceof HttpException) {
        HttpException httpException = (HttpException) e;
        ex = new ResponeThrowable(e, ERROR.HTTP_ERROR);
        switch (httpException.code()) {
            case UNAUTHORIZED:
            case FORBIDDEN:
            case NOT_FOUND:
            case REQUEST_TIMEOUT:
            case GATEWAY_TIMEOUT:
            case INTERNAL_SERVER_ERROR:
            case BAD_GATEWAY:
            case SERVICE_UNAVAILABLE:
            default:
                //ex.code = httpException.code();
                ex.message = "    ";
                break;
        }
        return ex;
    } else if (e instanceof java.net.UnknownHostException) {
        ex = new ResponeThrowable(e, ERROR.SSL_ERROR);
        ex.message = "    ";

        return ex;
    } else {
        ex = new ResponeThrowable(e, ERROR.UNKNOWN);
        ex.message = "    ";

        return ex;
    }
}

class ERROR {
    /**
     *     
     */
    public static final int UNKNOWN = 1000;
    /**
     *     
     */
    public static final int HTTP_ERROR = 1003;

    /**
     *     
     */
    public static final int SSL_ERROR = 1005;
}

public static class ResponeThrowable extends Exception {
    public int code;
    public String message;

    public ResponeThrowable(Throwable throwable, int code) {
        super(throwable);
        this.code = code;
    }
}

}
//使用.subscribe(new Observer() { @Override public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext() {
             
                    }

                    @Override
                    public void onError(Throwable e) {
                    if(e instanceof Exception){
                            //       Exception
                            Log.i("TAG",":code::"+ ExceptionHandle.handleException(e).code);
                            Log.i("TAG","message"+ ExceptionHandle.handleException(e).message);
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });