(我想引用另外一個問題作爲參考:How do I elegantly check many conditions in Erlang?)二郎:成功案例和錯誤處理事務
的「從錯誤處理是分開的成功案例代碼」通用的形式似乎是:
try
ok = do_x(),
...
ok = do_y()
catch
error:{badmatch, x_failure} -> do_something1();
...
error:{badmatch, y_failure} -> do_something2();
當try子句中的函數執行某些副作用時,如寫入文件,發送網絡數據包,將數據寫入數據庫等,如何使用此模式?在catch子句中是否有一個「回滾」的通用模式?例如:
try
%How to make this whole block a transaction?
ok = step_1_write_file(),
ok = step_2_write_database(),
ok = step_3_send_packet(),
...
catch
error:{badmatch, database_failure} -> clean_up_step_1() %delete file?
error:{badmatch, sendpacket_failure} -> clean_up_step_1_and_2() %??
這似乎是錯誤處理變得繁重,其中需要被執行的清理是依賴於try
塊失敗的步驟。
有沒有把這個作爲一個交易一般的編程模式,而在try塊的成功步驟失敗從句前是``解開「?
成功_typing_在這裏似乎並不相關。 –
@AlexeyRomanov問題標題編輯 – Tommy