Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle the `IllegalArgumentException` in RxJava?

I'm using Retrofit with RxJava for the network calls and RxBinding for view operations. In signup screen, upon clicking 'Register' button I'm posting the info to the local server using the MyApi service.

SignupActivity.class

mCompositeSubscription.add(RxView.clicks(mRegisterButton).debounce(300, TimeUnit.MILLISECONDS).
            subscribe(view -> {
              registerUser();
            }, e -> {
              Timber.e(e, "RxView ");
              onRegistrationFailed(e.getMessage());
            }));

private void registerUser() {
 mCompositeSubscription.add(api.registerUser(mEmail,
        mPassword, mConfirmPassword)
        .subscribe(user -> {
          Timber.d("Received user object. Id: " + user.getUserId());
        }, e -> {
          Timber.e(e, "registerUser() ");
          onRegistrationFailed(e.getMessage());
        }));
  }

MyApi.class

 public Observable<User> registerUser(String username, String password, String confirmPassword) {
    return mService.registerUser(username, password, confirmPassword)
        .compose(applySchedulers());
  }

  @SuppressWarnings("unchecked") <T> Observable.Transformer<T, T> applySchedulers() {
    return observable -> observable.subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread());
  }

MyService.class

  @FormUrlEncoded @POST("users/")
  Observable<User> registerUser(@Path("email") String username,
      @Path("password") String password, @Path("password_confirmation") String confirmPassword);

The call fails with IllegalArgumentException since I'm posting an invalid info.

What's my main issue is, upon IllegalArgumentException I thought RxJava would execute registerUser()#ErrorHandler() since my registerUser service call failed with exception but instead it calls RxView#ErrorHandler().

How can I make/force registerUser()#ErrorHandler() to take care of the exception occurred during the network call?

like image 263
blizzard Avatar asked Oct 30 '22 16:10

blizzard


1 Answers

My bad, the network call doesn't fail with IllegalArgumentException but the request construction itself failed with IllegalArgumentException.

java.lang.IllegalArgumentException: URL "users/" does not contain {email}". 

Instead of using @Field annotation for constructing the POST body , I'd mistakenly used @Path annotation.

The correct definition:

 @FormUrlEncoded @POST("users/")
 Observable<User> registerUser(@Field("email") String username,
      @Field("password") String password, @Field("password_confirmation") String confirmPassword);
like image 75
blizzard Avatar answered Nov 15 '22 05:11

blizzard