Observer.onError firing off inconsistently

一世执手 提交于 2019-12-21 03:58:27

问题


I am using Retrofit to access my API as follows:

public interface UserService {
    ...
    @POST("/user/login")
    public Observable<User> register(@Body() User user);
}

Here is how I access my API:

mUserService.register(user)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<User>() {
    @Override
    public void onCompleted() {
    ....
    }

    @Override
    public void onError(Throwable e) {
    ....
    }

    @Override
    public void onNext(User user) {
    ....
    }
});

This works perfectly well, except when there is an exception (i.e. IOException, or when connection times out), the onError method doesn't get fired, instead I get an exception on the main thread which terminates my application.

However, for some cases (such as when the API call responds with status code 400), the onError method is fired as expected.

After digging the logcat output, I have spotted this line, (not sure how I am supposed to deal with this)

rx.exceptions.OnErrorFailedException: Error occurred when trying to propagate error to Observer.onError

Can someone let me know where I am doing things wrong?


回答1:


In my previous experience with RxJava the OnErrorFailedException means that an exception occurred while handling another exception in the onError method.

If you don't see stack trace of the real cause it's probably due the bug in RxJava with CompositeException (versions 0.19.2 and above) https://github.com/Netflix/RxJava/issues/1405

As a workaround try to wrap your onError code within try-catch block and log the exception. This way you will see what's the problem with your onError implementation and you will be able to solve the problem.

@Override
public void onError(Throwable e) {
   try {
      ...
   catch(Throwable e) {
      // Log the exception
   }
}



回答2:


you can use unsafe unsafeSubscribe.

...
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.unsafeSubscribe(new Observer<User>() {
    @Override
    public void onCompleted() {
    ....
    }

    @Override
    public void onError(Throwable e) {
    ....
    }

    @Override
    public void onNext(User user) {
    ....
    }
});
...


来源:https://stackoverflow.com/questions/24860942/observer-onerror-firing-off-inconsistently

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!