简体   繁体   中英

How do I map errors in rxJava?

How do I transform an error returned by an Observable in rxJava? Now I have this method:


@Override
    public Maybe<JsonObject> getUser(String token) {
        return tokenManager.getTokenInfo(token)    //returns a Single<UserInfo>
            .flatMapMaybe(userInfo -> userRepo.findOne(userInfo));
    }

The behavior is that any exception that is passed by getTokenInfo or findOne is propagated to the subscriber of this function's return value. Is it possible to map the exceptions to something else? Like

@Override
    public Maybe<JsonObject> getUser(String token) {
        return tokenManager.getTokenInfo(token)
            mapError(exc -> new AuthException("invalid token"))  //don't let subscriber get raw exc
            .flatMapMaybe(userInfo -> userRepo.findOne(userInfo))
            .mapError(exc -> new NetworkException());


    }

Use onErrorResumeNext with an error source of the desired exception:

return tokenManager.getTokenInfo(token)
       .onErrorResumeNext(exc -> Single.error(new AuthException("invalid token")))
       .flatMapMaybe(userInfo -> userRepo.findOne(userInfo))
       .onErrorResumeNext(exc -> Maybe.error(new NetworkException()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM