RxPY - 錯誤處理運算子
catch
此運算子會在出現異常時終止源可觀察物件。
語法
catch(handler)
引數
handler:當源可觀察物件出現錯誤時會發出此可觀察物件。
返回值
它將返回一個可觀察物件,該物件將包含來自源可觀察物件的錯誤之前的的值及來自處理程式可觀察物件的值。
示例
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)))
在此示例中,當源可觀察物件的值為 4 時,我們建立了一個異常,因此,第一個可觀察物件在此處終止,然後是處理程式的值。
輸出
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
出現錯誤時,此運算子將對源可觀察物件進行重試,並且完成重試次數後將終止。
語法
retry(count)
引數
count:如果源可觀察物件出現錯誤時,重試的次數。
返回值
它將根據指定的重試次數以重複序列的形式返回來自源可觀察物件的可觀察物件。
示例
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!
廣告