Jai
Jai

Reputation: 399

Java Vavr : Log Exception on Failure

I want to log exceptions while using VAVR (formerly javaslang). Below is the sample code snippet.

    //will get 500 as response from this url
    String sampleurl    =   "http://someurl.com";
    List<String>    myList  =   List.of(sampleurl);
    LOGGER.info("In {} with urls {}",getClass(),myList);        

    return Observable.from(myList).flatMap(url ->

            Observable.create(subscriber -> {

                Try<String> httpEntity  = HttpUtil.retrieveData(url).flatMap(httpResponse -> Try.of( () -> EntityUtils.toString(httpResponse.getEntity())));
                httpEntity
                        .andThen(subscriber::onNext)
                        .andThen(subscriber::onCompleted)
                        .onFailure(subscriber::onError);

            }));

I am trying to log exception in the onFailure() block but nothing gets logged. Please advise me on this.

Regards, Jai

Upvotes: 1

Views: 2834

Answers (1)

Daniel Dietrich
Daniel Dietrich

Reputation: 2272

In both cases, success and failure, Vavr works as expected. Here are simple tests:

// prints nothing
Try.success("ok")
        .andThen(() -> {})
        .andThen(() -> {})
        .onFailure(System.out::println);

// prints "java.lang.Error: ok"
Try.failure(new Error("ok"))
        .andThen(() -> {})
        .andThen(() -> {})
        .onFailure(System.out::println);

I see two possible answers why the failure is not logged in your example:

  1. the logger configuration does not fit your needs
  2. the observables are not processed and Try is never called

Disclamer: I'm the creator of Vavr

Upvotes: 2

Related Questions