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());
}
CodePudding user response:
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()));