RxPY - Error Handling Operators



catch

This operator will terminate the source observable when there is an exception.

Syntax

catch(handler)

Parameters

handler: This observable will be emitted, when the source observable has an error.

Return value

It will return an observable, that will have values from the source observable before the error, followed by values from 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 have created an exception, when the source value from the observable is 4, so the first observable is terminated there and later followed by the values 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

This operator will retry on the source observable when there is an error and once the retry count is done it will terminate.

Syntax

retry(count)

Parameters

count: the number of times to retry if there is an error from the source observable.

Return value

It will return an observable from the source observable in repeated sequence as per the retry count given.

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 error cannot proceed!
Advertisements