Answer the question
In order to leave comments, you need to log in
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));
@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);
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question