-
Notifications
You must be signed in to change notification settings - Fork 48
Error Handling
From version 1.2.0, ReactFX includes an error-reporting mechanism. This mechanism is used to report errors thrown by user-provided functions, such as a subscriber, a function passed to map(), etc.
- Does not force the user to handle errors.
- Stream combinators propagate errors.
- Possible to cut off error propagation by explicitly handling the errors.
- Possible to monitor errors on a stream without turning a lazily bound stream into an eagerly bound one.
- Possible to transparently hook into errors flowing through any stream (e.g. stream that is in the middle of a stream chain).
To observe errors of a stream, one uses the monitor(Consumer<Throwable>) method.
EventStream<T> stream = ...;
stream.monitor(error -> handle(error));Note that due to lazy nature of streams, a stream will only report errors if it also has at least one subscriber.
Alternatively, one can use the errors() method to obtain a stream of errors reported by an event stream:
EventStream<T> stream = ...;
EventStream<Throwable> errors = stream.errors();Neither of the above methods consume errors, but errors are propagated to any stream based on the original stream. In the following code:
EventStream<T> stream = ...;
stream.monitor(error -> handle(error));
EventStream<U> mapped = stream.map(t -> f(t));mapped reports the same errors as stream, plus any errors thrown by its own subscribers or the function f.
To stop downstream propagation of errors, one uses the handleErrors(Consumer<Throwable>) method:
EventStream<T> stream = ...;
EventStream<T> handled = stream.handleErrors(error -> handle(error));Here, handled does not propagate any errors reported by stream. It may still report errors thrown by its own subscribers, though.
materializeErrors() makes errors reported by a stream explicit by turning them into valid events emitted by the returned stream:
EventStream<T> stream = ...;
EventStream<Try<T>> materialized = stream.materializeErrors();
materialized.subscribe(t -> {
if(t.isSuccess()) {
doSomething(t.get());
} else {
handleException(t.getFailure());
}
});materialized does not propagate any errors reported by stream, but may report errors when its own subscribers throw an exception.