Search in sources :

Example 6 with HttpException

use of com.jakewharton.retrofit2.adapter.rxjava2.HttpException in project AndroidUtilLib by SiberiaDante.

the class NetException method throwable.

public static ResponseThrowable throwable(Throwable e) {
    ResponseThrowable ex;
    // }
    if (e instanceof HttpException) {
        HttpException httpException = (HttpException) e;
        ex = new ResponseThrowable(e, ERROR.HTTP_ERROR);
        switch(httpException.code()) {
            case REQUEST_TIMEOUT:
            case GATEWAY_TIMEOUT:
                ex.message = "请求超时,请检查网络";
                break;
            case UNAUTHORIZED:
            case FORBIDDEN:
            case NOT_FOUND:
            // 500
            case INTERNAL_SERVER_ERROR:
            case BAD_GATEWAY:
            case SERVICE_UNAVAILABLE:
            case ACCESS_DENIED:
                ex.message = "网络异常";
                break;
            default:
                ex.message = "网络错误";
                break;
        }
        return ex;
    } else if (e instanceof RuntimeException) {
        ex = new ResponseThrowable(e, ERROR.RUNTIME);
        ex.message = "RuntimeException: " + e.getMessage();
        return ex;
    } else if (e instanceof JSONException || e instanceof ParseException) {
        ex = new ResponseThrowable(e, ERROR.PARSE_ERROR);
        ex.message = "解析错误";
        return ex;
    } else if (e instanceof ConnectException) {
        ex = new ResponseThrowable(e, ERROR.NETWORD_ERROR);
        ex.message = "网络连接失败";
        return ex;
    } else if (e instanceof java.security.cert.CertPathValidatorException) {
        ex = new ResponseThrowable(e, ERROR.SSL_NOT_FOUND);
        ex.message = "证书路径没找到";
        return ex;
    } else if (e instanceof javax.net.ssl.SSLHandshakeException) {
        ex = new ResponseThrowable(e, ERROR.SSL_ERROR);
        ex.message = "证书验证失败";
        return ex;
    } else if (e instanceof java.net.SocketTimeoutException) {
        ex = new ResponseThrowable(e, ERROR.TIMEOUT_ERROR);
        ex.message = "连接超时,请稍后重试";
        return ex;
    } else {
        ex = new ResponseThrowable(e, ERROR.UNKNOWN);
        if (!SDNetWorkUtil.isNetWorkConnected()) {
            ex.message = "网络未连接";
        } else if (!SDNetWorkUtil.isAvailableByPing()) {
            ex.message = "网络不可用";
        } else {
            ex.message = "未知错误";
        }
        return ex;
    }
}
Also used : JSONException(org.json.JSONException) HttpException(com.jakewharton.retrofit2.adapter.rxjava2.HttpException) ParseException(android.net.ParseException) ConnectException(java.net.ConnectException)

Example 7 with HttpException

use of com.jakewharton.retrofit2.adapter.rxjava2.HttpException in project talk-android by nextcloud.

the class ContactsController method fetchData.

private void fetchData() {
    dispose(null);
    Set<Sharee> shareeHashSet = new HashSet<>();
    contactItems = new ArrayList<>();
    userHeaderItems = new HashMap<>();
    RetrofitBucket retrofitBucket = ApiUtils.getRetrofitBucketForContactsSearch(userEntity.getBaseUrl(), "");
    contactsQueryDisposable = ncApi.getContactsWithSearchParam(ApiUtils.getCredentials(userEntity.getUsername(), userEntity.getToken()), retrofitBucket.getUrl(), retrofitBucket.getQueryMap()).subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()).subscribe((ShareesOverall shareesOverall) -> {
        if (shareesOverall != null) {
            if (shareesOverall.getOcs().getData().getUsers() != null) {
                shareeHashSet.addAll(shareesOverall.getOcs().getData().getUsers());
            }
            if (shareesOverall.getOcs().getData().getExactUsers() != null && shareesOverall.getOcs().getData().getExactUsers().getExactSharees() != null) {
                shareeHashSet.addAll(shareesOverall.getOcs().getData().getExactUsers().getExactSharees());
            }
            Participant participant;
            for (Sharee sharee : shareeHashSet) {
                if (!sharee.getValue().getShareWith().equals(userEntity.getUsername())) {
                    participant = new Participant();
                    participant.setName(sharee.getLabel());
                    String headerTitle;
                    headerTitle = sharee.getLabel().substring(0, 1).toUpperCase();
                    UserHeaderItem userHeaderItem;
                    if (!userHeaderItems.containsKey(headerTitle)) {
                        userHeaderItem = new UserHeaderItem(headerTitle);
                        userHeaderItems.put(headerTitle, userHeaderItem);
                    }
                    participant.setUserId(sharee.getValue().getShareWith());
                    contactItems.add(new UserItem(participant, userEntity, userHeaderItems.get(headerTitle)));
                }
            }
            userHeaderItems = new HashMap<>();
            Collections.sort(contactItems, (o1, o2) -> {
                String firstName;
                String secondName;
                if (o1 instanceof UserItem) {
                    firstName = ((UserItem) o1).getModel().getName();
                } else {
                    firstName = ((UserHeaderItem) o1).getModel();
                }
                if (o2 instanceof UserItem) {
                    secondName = ((UserItem) o2).getModel().getName();
                } else {
                    secondName = ((UserHeaderItem) o2).getModel();
                }
                return firstName.compareToIgnoreCase(secondName);
            });
            if (isNewConversationView) {
                contactItems.add(0, new NewCallHeaderItem());
            }
            adapter.updateDataSet(contactItems, true);
            searchItem.setVisible(contactItems.size() > 0);
            swipeRefreshLayout.setRefreshing(false);
            if (isNewConversationView) {
                checkAndHandleBottomButtons();
            }
        }
    }, throwable -> {
        if (searchItem != null) {
            searchItem.setVisible(false);
        }
        if (throwable instanceof HttpException) {
            HttpException exception = (HttpException) throwable;
            switch(exception.code()) {
                case 401:
                    if (getParentController() != null && getParentController().getRouter() != null) {
                        getParentController().getRouter().pushController((RouterTransaction.with(new WebViewLoginController(userEntity.getBaseUrl(), true)).pushChangeHandler(new VerticalChangeHandler()).popChangeHandler(new VerticalChangeHandler())));
                    }
                    break;
                default:
                    break;
            }
        }
        swipeRefreshLayout.setRefreshing(false);
        dispose(contactsQueryDisposable);
    }, () -> {
        swipeRefreshLayout.setRefreshing(false);
        dispose(contactsQueryDisposable);
    });
}
Also used : AutoInjector(autodagger.AutoInjector) Bundle(android.os.Bundle) UserUtils(com.nextcloud.talk.utils.database.user.UserUtils) EntryMenuController(com.nextcloud.talk.controllers.bottomsheet.EntryMenuController) IFlexible(eu.davidea.flexibleadapter.items.IFlexible) SearchView(android.support.v7.widget.SearchView) RetrofitBucket(com.nextcloud.talk.models.RetrofitBucket) UserItem(com.nextcloud.talk.adapters.items.UserItem) AndroidSchedulers(io.reactivex.android.schedulers.AndroidSchedulers) OnClick(butterknife.OnClick) DividerItemDecoration(android.support.v7.widget.DividerItemDecoration) BindView(butterknife.BindView) ApiUtils(com.nextcloud.talk.utils.ApiUtils) ViewHidingBehaviourAnimation(com.nextcloud.talk.utils.animations.ViewHidingBehaviourAnimation) BottomSheet(com.kennyc.bottomsheet.BottomSheet) Handler(android.os.Handler) View(android.view.View) Button(android.widget.Button) UserHeaderItem(com.nextcloud.talk.adapters.items.UserHeaderItem) Schedulers(io.reactivex.schedulers.Schedulers) Sharee(com.nextcloud.talk.models.json.sharees.Sharee) SelectableAdapter(eu.davidea.flexibleadapter.SelectableAdapter) VerticalChangeHandler(com.bluelinelabs.conductor.changehandler.VerticalChangeHandler) Participant(com.nextcloud.talk.models.json.participants.Participant) MenuItemCompat(android.support.v4.view.MenuItemCompat) Optional(butterknife.Optional) HttpException(retrofit2.HttpException) InputType(android.text.InputType) Set(java.util.Set) FlexibleAdapter(eu.davidea.flexibleadapter.FlexibleAdapter) ThreadMode(org.greenrobot.eventbus.ThreadMode) ViewGroup(android.view.ViewGroup) BundleKeys(com.nextcloud.talk.utils.bundle.BundleKeys) List(java.util.List) Disposable(io.reactivex.disposables.Disposable) Parcels(org.parceler.Parcels) FastScroller(eu.davidea.fastscroller.FastScroller) AbstractFlexibleItem(eu.davidea.flexibleadapter.items.AbstractFlexibleItem) Nullable(android.support.annotation.Nullable) SearchManager(android.app.SearchManager) EditorInfo(android.view.inputmethod.EditorInfo) Context(android.content.Context) CoordinatorLayout(android.support.design.widget.CoordinatorLayout) UserEntity(com.nextcloud.talk.models.database.UserEntity) SmoothScrollLinearLayoutManager(eu.davidea.flexibleadapter.common.SmoothScrollLinearLayoutManager) Intent(android.content.Intent) HashMap(java.util.HashMap) NonNull(android.support.annotation.NonNull) MenuItem(android.view.MenuItem) ArrayList(java.util.ArrayList) BottomSheetLockEvent(com.nextcloud.talk.events.BottomSheetLockEvent) HashSet(java.util.HashSet) Inject(javax.inject.Inject) BaseController(com.nextcloud.talk.controllers.base.BaseController) MenuInflater(android.view.MenuInflater) EventBus(org.greenrobot.eventbus.EventBus) Menu(android.view.Menu) SwipeRefreshLayout(android.support.v4.widget.SwipeRefreshLayout) NcApi(com.nextcloud.talk.api.NcApi) BottomNavigationView(android.support.design.widget.BottomNavigationView) R(com.nextcloud.talk.R) Room(com.nextcloud.talk.models.json.rooms.Room) LayoutInflater(android.view.LayoutInflater) NewCallHeaderItem(com.nextcloud.talk.adapters.items.NewCallHeaderItem) TextUtils(android.text.TextUtils) FlipView(eu.davidea.flipview.FlipView) ShareesOverall(com.nextcloud.talk.models.json.sharees.ShareesOverall) HorizontalChangeHandler(com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler) RecyclerView(android.support.v7.widget.RecyclerView) Subscribe(org.greenrobot.eventbus.Subscribe) KeyboardUtils(com.nextcloud.talk.utils.KeyboardUtils) CallActivity(com.nextcloud.talk.activities.CallActivity) Observer(io.reactivex.Observer) ViewTreeObserver(android.view.ViewTreeObserver) RoomOverall(com.nextcloud.talk.models.json.rooms.RoomOverall) Collections(java.util.Collections) NextcloudTalkApplication(com.nextcloud.talk.application.NextcloudTalkApplication) RouterTransaction(com.bluelinelabs.conductor.RouterTransaction) RetrofitBucket(com.nextcloud.talk.models.RetrofitBucket) HashMap(java.util.HashMap) NewCallHeaderItem(com.nextcloud.talk.adapters.items.NewCallHeaderItem) VerticalChangeHandler(com.bluelinelabs.conductor.changehandler.VerticalChangeHandler) UserItem(com.nextcloud.talk.adapters.items.UserItem) Sharee(com.nextcloud.talk.models.json.sharees.Sharee) UserHeaderItem(com.nextcloud.talk.adapters.items.UserHeaderItem) Participant(com.nextcloud.talk.models.json.participants.Participant) ShareesOverall(com.nextcloud.talk.models.json.sharees.ShareesOverall) HttpException(retrofit2.HttpException) HashSet(java.util.HashSet)

Example 8 with HttpException

use of com.jakewharton.retrofit2.adapter.rxjava2.HttpException in project BaseProject by wareine.

the class ExceptionHandle method handleException.

public static ResponseException handleException(Throwable e) {
    ResponseException ex;
    if (e instanceof HttpException) {
        HttpException httpException = (HttpException) e;
        ex = new ResponseException(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.message = "网络错误";
                break;
        }
        return ex;
    } else if (e instanceof ServerException) {
        ServerException resultException = (ServerException) e;
        ex = new ResponseException(resultException, resultException.code);
        ex.message = resultException.message;
        return ex;
    } else if (e instanceof JsonParseException || e instanceof JSONException || e instanceof ParseException) {
        ex = new ResponseException(e, ERROR.PARSE_ERROR);
        ex.message = "解析错误";
        return ex;
    } else if (e instanceof ConnectException) {
        ex = new ResponseException(e, ERROR.NETWORD_ERROR);
        ex.message = "连接失败";
        return ex;
    } else if (e instanceof javax.net.ssl.SSLHandshakeException) {
        ex = new ResponseException(e, ERROR.SSL_ERROR);
        ex.message = "证书验证失败";
        return ex;
    } else if (e instanceof ConnectTimeoutException) {
        ex = new ResponseException(e, ERROR.TIMEOUT_ERROR);
        ex.message = "连接超时";
        return ex;
    } else if (e instanceof java.net.SocketTimeoutException) {
        ex = new ResponseException(e, ERROR.TIMEOUT_ERROR);
        ex.message = "连接超时";
        return ex;
    } else {
        ex = new ResponseException(e, ERROR.UNKNOWN);
        ex.message = "未知错误";
        return ex;
    }
}
Also used : JSONException(org.json.JSONException) HttpException(retrofit2.HttpException) JsonParseException(com.google.gson.JsonParseException) ParseException(android.net.ParseException) JsonParseException(com.google.gson.JsonParseException) ConnectException(java.net.ConnectException) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 9 with HttpException

use of com.jakewharton.retrofit2.adapter.rxjava2.HttpException in project RxReddit by damien5314.

the class RedditAuthService method refreshUserAccessToken.

@Override
public Observable<UserAccessToken> refreshUserAccessToken() {
    return Observable.defer(() -> {
        UserAccessToken token = getUserAccessToken();
        if (token == null) {
            return Observable.error(new IllegalStateException("No user access token available"));
        }
        if (token.secondsUntilExpiration() > EXPIRATION_THRESHOLD) {
            return Observable.just(token);
        }
        String refreshToken = token.getRefreshToken();
        if (refreshToken == null) {
            clearUserAccessToken();
            return Observable.error(new IllegalStateException("No refresh token available"));
        }
        String grantType = "refresh_token";
        return authService.refreshUserAuthToken(grantType, refreshToken).flatMap(RxRedditUtil::responseToBody).doOnNext(this::saveUserAccessToken).doOnError(error -> {
            if (error instanceof HttpException && ((HttpException) error).code() == 403) {
                // 403 means our refresh token is no longer good, just discard it
                clearUserAccessToken();
            }
        });
    });
}
Also used : UserAccessToken(rxreddit.model.UserAccessToken) HttpException(retrofit2.HttpException) RxRedditUtil(rxreddit.util.RxRedditUtil)

Example 10 with HttpException

use of com.jakewharton.retrofit2.adapter.rxjava2.HttpException in project bdcodehelper by boredream.

the class LcErrorConstants method parseHttpErrorInfo.

/**
 * 解析服务器错误信息
 */
public static String parseHttpErrorInfo(Throwable throwable) {
    String errorInfo = throwable.getMessage();
    if (throwable instanceof HttpException) {
        // 如果是Retrofit的Http错误,则转换类型,获取信息
        HttpException exception = (HttpException) throwable;
        ResponseBody responseBody = exception.response().errorBody();
        MediaType type = responseBody.contentType();
        // 如果是application/json类型数据,则解析返回内容
        if (type != null && type.type().equals("application") && type.subtype().equals("json")) {
            try {
                // 这里的返回内容是Bmob/AVOS/Parse等RestFul API文档中的错误代码和错误信息对象
                BaseResponse errorResponse = new Gson().fromJson(responseBody.string(), BaseResponse.class);
                errorInfo = getLocalErrorInfo(errorResponse);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    } else if (throwable instanceof LcErrorResponse) {
        LcErrorResponse lce = (LcErrorResponse) throwable;
        errorInfo = getLocalErrorInfo(lce.getError());
    } else {
        if (throwable instanceof UnknownHostException) {
            errorInfo = "无法连接到服务器";
        }
    }
    return errorInfo;
}
Also used : BaseResponse(com.boredream.bdcodehelper.lean.entity.BaseResponse) UnknownHostException(java.net.UnknownHostException) MediaType(okhttp3.MediaType) Gson(com.google.gson.Gson) HttpException(retrofit2.HttpException) LcErrorResponse(com.boredream.bdcodehelper.lean.entity.LcErrorResponse) HttpException(retrofit2.HttpException) UnknownHostException(java.net.UnknownHostException) ResponseBody(okhttp3.ResponseBody)

Aggregations

HttpException (retrofit2.HttpException)29 JSONException (org.json.JSONException)12 JsonParseException (com.google.gson.JsonParseException)11 ConnectException (java.net.ConnectException)10 ParseException (android.net.ParseException)8 SocketTimeoutException (java.net.SocketTimeoutException)7 UnknownHostException (java.net.UnknownHostException)7 Disposable (io.reactivex.disposables.Disposable)6 IOException (java.io.IOException)6 Response (retrofit2.Response)5 TextUtils (android.text.TextUtils)4 CompositeDisposable (io.reactivex.disposables.CompositeDisposable)4 Test (org.junit.Test)4 NonNull (android.support.annotation.NonNull)3 Gson (com.google.gson.Gson)3 AccessTokenRequest (com.khmelenko.lab.varis.network.request.AccessTokenRequest)3 AuthorizationRequest (com.khmelenko.lab.varis.network.request.AuthorizationRequest)3 AccessToken (com.khmelenko.lab.varis.network.response.AccessToken)3 Authorization (com.khmelenko.lab.varis.network.response.Authorization)3 AndroidSchedulers (io.reactivex.android.schedulers.AndroidSchedulers)3