错误,中止,断言和失败之间的区别?

Difference between error, abort, assert and fail?

DAML 中的errorfailabortassert 有什么区别?

failabort 是同一函数的别名,abort 是更常见的用法。它们用于使 Action 失败,例如 UpdateScenario,但仍然是 return 适当类型的值。以下场景完全没问题,因为 s 从未实际执行过:

t = scenario do
  let
    s : Scenario () = abort "Foo"
  return ()

当你想让ScenarioUpdate的分支导致失败时,使用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用于定义偏函数。它不会 return 一个值,但会导致解释器立即退出并显示给定的错误消息。例如

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 ()