D
D
Dmitry Serkov2016-10-24 20:32:19
Java
Dmitry Serkov, 2016-10-24 20:32:19

Retrofit 2 and RXJava how to properly handle exceptions?

Hello.
There is a site where authorization occurs by Post request with the transfer of login and password.
Is it correct to handle exceptions in a bunch of Retrofit and RXJava like this:
apiService.login returns an Observable ResponseBody

apiService.login(login, pass)
                        .map(responseBody -> {
                            try {
                                return responseBody.string();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            return "";
                        })
                        .subscribeOn(Schedulers.newThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(s -> System.out.println(s));

interface
@FormUrlEncoded
    @POST("/login.php")
    Observable<ResponseBody> login(
            @Field("login") String login,
            @Field("pass") String pass);

public SiteService(Context context) {

        cookieJar = new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(context));

        okHttpClient = new OkHttpClient.Builder()
                .cookieJar(cookieJar)
                .build();

        client = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(okHttpClient)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();


        apiService = client.create(SiteApi.class);
    }
    public Observable<ResponseBody> login(String login, String pass){

        return apiService.login(login, pass);
    }

Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Y
Yuri, 2016-10-25
@Hutaab

nah, wrong. Add onError() after the login call. You can read here

D
davidnum95, 2016-10-25
@davidnum95

The error is returned to the subscriber in the OnError(Exception throwable) method, respectively:

apiService.login(login, pass)
                        .map(responseBody -> {
                            try {
                                return responseBody.string();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            return "";
                        })
                        .subscribeOn(Schedulers.newThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(s -> System.out.println(s), throwable -> {
                                        // тут обработка ошибок
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question