RxPY – Error Handling Operators
RxPY – Error Handling Operators
catch
This operator terminates the source observer when an exception occurs.
Syntax
catch(handler)
Parameters
handler: This observer will be emitted when an error occurs in the source observer.
Return Value
This returns an observable containing the value of the source observable before the error, followed by the value of the handler observable.
Example
from rx import of, operators as op
from datetime import date
test = of(1,2,3,4,5,6)
handler = of(11,12,13,14)
def casetest(e):
if (e==4):
raise Exception('err')
else:
return e
sub1 = test.pipe(
op.map(lambda e : casetest(e)),
op.catch(handler)
)
sub1.subscribe(lambda x: print("The value is {0}".format(x)),
on_error = lambda e: print("Error : {0}".format(e)))
In this example, we create an exception when the source value from the observer is 4, so the first observer is terminated there, followed by the value from the handler.
Output
E:pyrx>python testrx.py
The value is 1
The value is 2
The value is 3
The value is 11
The value is 12
The value is 13
The value is 14
retry
When an error occurs, this operator will retry on the source observable and terminate once the number of retries has been completed.
Syntax
retry(count)
Parameters
Count: The number of retries to perform if an error occurs on the source observer.
Return Value
This function returns an observer from the source observer in a repeated order, based on the given number of retries.
Example
from rx import of, operators as op
test = of(1,2,3,4,5,6)
def casetest(e):
if (e==4):
raise Exception('There is error cannot proceed!')
else:
return e
sub1 = test.pipe(
op.map(lambda e : casetest(e)),
op.retry(2)
)
sub1.subscribe(lambda x: print("The value is {0}".format(x)),
on_error = lambda e: print("Error : {0}".format(e)))
Output
E:pyrx>python testrx.py
The value is 1
The value is 2
The value is 3
The value is 1
The value is 2
The value is 3
Error: There is an error cannot proceed!