The catch_exception operator

The catch_exception operator allows us to catch any error coming from its source observable and to continue to emit items. When the error occurs in the source observable, the catch_exception operator continues the sequence with another sequence of items. Its marble diagram is shown in the following figure:

Figure 4.15: The catch_exception operator

Its prototype is as follows:

Observable.catch_exception(self, second=None, handler=None):

The optional second argument is either an observable to chain when an error occurs in the source observable or a function that returns an observable. The optional handler argument is an exception handler that must return a future. This future will be wrapped in an observable. Only one of the two arguments must be used. The following is an example of this operator:

err = Observable.throw("error!")
err.catch_exception(lambda e: Observable.from_([1,2,3]))
.subscribe(
on_next=lambda i: print("item: {}".format(i)),
on_error=lambda e: print("error: {}".format(e)),
on_completed=lambda: print("completed")
)

The following is the output of this example:

item: 1
item: 2
item: 3
completed

The error has been caught correctly and has been replaced with another observable.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.77.208