RxPY - 错误处理运算符
-
catch
当出现异常时,此运算符将终止源 observable。句法
catch(handler)
参数
handler:当源 observable 有错误时,这个 observable 将被发射。返回值
它将返回一个可观察对象,该可观察对象在错误之前具有来自可观察源的值,然后是来自可观察处理程序的值。例子
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)))
在这个例子中,我们创建了一个异常,当来自 observable 的源值为 4 时,所以第一个 observable 在那里终止,然后是来自处理程序的值。输出
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
当出现错误时,此运算符将重试源 observable,一旦重试计数完成,它将终止。句法
retry(count)
参数
count:如果源 observable 出现错误,重试的次数。返回值
它将根据给定的重试计数以重复的顺序从源 observable 返回一个 observable。例子
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)))
输出
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!