【发布时间】:2019-09-04 07:45:22
【问题描述】:
DAML 中的error、fail、abort 和 assert 有什么区别?
【问题讨论】:
标签: daml
DAML 中的error、fail、abort 和 assert 有什么区别?
【问题讨论】:
标签: daml
fail 和 abort 是同一函数的别名,abort 是更常见的用法。它们用于使Action 失败,如Update 和Scenario,但仍返回适当类型的值。以下场景非常好,因为s 从未实际执行过:
t = scenario do
let
s : Scenario () = abort "Foo"
return ()
如果您希望 Scenario 或 Update 的分支导致失败,请使用 abort。例如,下面的Scenario会根据abortScenario的值成功或失败:
t2 = scenario do
let abortScenario = True
if abortScenario
then abort "Scenario was aborted"
else return ()
assert 只是abort 的包装器:
-- | Check whether a condition is true. If it's not, abort the transaction.
assert : CanAbort m => Bool -> m ()
assert = assertMsg "Assertion failed"
-- | Check whether a condition is true. If it's not, abort the transaction
-- with a message.
assertMsg : CanAbort m => Text -> Bool -> m ()
assertMsg msg b = if b then return () else abort msg
使用abortMsg 几乎总是更好,因为您可以提供信息丰富的错误消息。
error 用于定义偏函数。它不返回值,但会导致解释器立即退出并显示给定的错误消息。例如
divide : Int -> Int -> Int
divide x y
| y == 0 = error "Division by Zero!"
| otherwise = x / y
DAML 被急切地执行,所以你必须非常小心error。即使没有使用e,以下场景也会失败。
s = scenario do
let
e = divide 1 0
return ()
【讨论】: