2

I am new to the functional style of programming using vavr.

I have a method returns the data when its executed successfully and if it fails, it returns the MyCustomRunTimeException.

In my Service class, I am calling this API method, when API method fails I have to catch the exception and going to clear my application cache and return the same exception to the caller (another service method in my case).

if method call success I have to return the actual object, not the Try wrapped object.

How can I achieve this using vavr Try?

I tried to use different methods in vavr Try.recover but I am unable to throw the same exception.

Any sample example or snippet could be very helpful for me if some can provide.

Thanks in advance.

Example:

Foo doFoo() {
  throw new MyCustomRunTimeException();
}


method1(){

   try{
      doFoo();
  }catch(MyCustomRunTimeException ex){

clearcache();
  throw ex;
 }
}
Madhu
  • 552
  • 2
  • 10
  • 23

1 Answers1

1

Basically, if your function throws, you want to do something (in case of failure) then throw it again? How about this?

Foo doFoo() {
  throw new MyCustomRunTimeException();
}


Foo myService() {
  return Try.of(() -> doFoo())
    .onFailure(e -> clearCache())
    .getOrElseThrow(identity());
}

If I may: since you want to try functional style, we usually don't rely on exceptions in FP, instead we rely on types that represent possibility of failure, like Either<MyBusinessProblem, Foo>.

Then your code would look like:

Either<MyBusinessProblem, Foo> doFoo() {
  return Left.of(new MyBusinessProblem());
}


Either<MyBusinessProblem, Foo> doFoo() myService() {
  return doFoo()
    .peekLeft(businessProblem -> clearCache());
}

As a bonus, now your code is explicit and you don't risk forgetting handling an error.

Sir4ur0n
  • 1,753
  • 1
  • 13
  • 24
  • but in my case after clear the cache i have to re-throw the exception – Madhu Aug 11 '19 at 03:08
  • Have you tested my first solution? It will rethrow your exception. – Sir4ur0n Aug 13 '19 at 18:01
  • 1
    The problem there is that `.getOrElseThrow()` downcasting any catched exception into `Throwable`. So we have very poor control of exception type – chill appreciator Jan 13 '20 at 09:12
  • What do you mean, downcasting? The exception that will be thrown is still a MyCustomRunTimeException. You can still catch the MyCustomRunTimeException later. – Sir4ur0n Jan 13 '20 at 20:56