【发布时间】:2016-11-19 08:30:31
【问题描述】:
(我想引用另一个问题作为参考: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 块中的成功步骤是“unwound”?
【问题讨论】:
-
成功 打字 似乎与这里无关。
-
@AlexeyRomanov 问题标题已编辑
标签: erlang