How do I handle response errors using with Retrofit and RxJava/RxAndroid?

杀马特。学长 韩版系。学妹 提交于 2019-12-06 03:14:43

I have found a solution

Firstly I expanded my Token object to have an error property.

public class Token {

    private String token;
    private String error;

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public String getError() {
        return error;
    }

    public void setError(String error) {
        this.error = error;
    }

    @Override
    public String toString() {
        return token;
    }
}

Then I added an operator to my RxJava chain which can check to see if the error field is not null. And if there is an error, throw a custom exception which calls the subscribers onError allowing me to handle it.

if (token.getError() != null) {
    throw OnErrorThrowable.from(new UserAuthenticationException(token.getError()));
    }

And if there is an error, throw a custom exception which calls the subscribers onError allowing me to handle it.

if (e instanceof OnErrorThrowable){
    if (e.getCause() instanceof UserAuthenticationException){
        Log.d(TAG, "onError "+e.getCause().getMessage());
    }
    e.getCause().printStackTrace();
}

This is a bit late but if anyone wanders here, Retrofit 2 passes in instance of HttpException into the onError callback whenever the request returned from the server with an error code outside the [200,300) interval ...

throwable -> {
    if(throwable instanceof HttpException){
        switch(((HttpException)throwable).code()){
            // your error handling logic 
        }
    }
}

You can also retrieve the whole reponse from this object..

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