using vavr how to catch and re-throw the same exception

5.5k Views Asked by At

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;
 }
}
1

There are 1 best solutions below

4
On

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.