Skip to content

Error handling with onFail

johnmcclean-aol edited this page Feb 28, 2015 · 1 revision

onFail takes an optional Exception class type and a recovery function.

Recovery Functions

Recovery functions accept a SimpleReactFailedStageException as input.

  • Calling getValue() on this will return the input value into the previous stage that failed.
  • Calling getCause() will return the Exception that was thrown by the previous stage

Recovery functions return a replacement value for the work of the failed stage as their output (for example a default value).

Exception class types

onFail can also take an Exception class as an input parameter. Where those are specified onFail will only react to the specified exception type.

e.g.

   new LazyReact().react(()->1,()->2)
		.then(this::throwException)
		.onFail(IOException.class,this::handleException);

In the above example handleException will be called if throwException throws an IOException

Hierarchical Exception handling

Similar to the way that Java code handles try / catch statements, onFail with Exception types can be chained, and will attempt to recover from a given exception by using the onFails in order.

e.g.

 new EagerReact().react(()->1,()->2)
     .then(this::makeRestRequests)
     .onFail(TimeoutException.class, e-> markHostUnreachable(e.getValue()) )
     .onFail(InvalidResponseException.class, e->  markHostCommunicationIssue(e.getValue())
     .onFail(Throwable.class, e-> handleUnexpectedException(e))
     .onFail(IOException.class,this::handleIOException)
     .collect(Collectors.toList());

In this example we will

  • Mark hosts unreachable if a TimeoutException occurs when making requests
  • Mark hosts with a communication issue if an InvalidResponseException occurs
  • Handle all other exceptions with the handleUnexpectedException method
  • The handleIOException method will never be called as all types of exception will be handled by the previous onFail (Throwable.class, e-> handleUnexpectedException(e))
Clone this wiki locally