【问题标题】:Difference between error, abort, assert and fail?错误,中止,断言和失败之间的区别?
【发布时间】:2019-09-04 07:45:22
【问题描述】:

DAML 中的errorfailabortassert 有什么区别?

【问题讨论】:

    标签: daml


    【解决方案1】:

    failabort 是同一函数的别名,abort 是更常见的用法。它们用于使Action 失败,如UpdateScenario,但仍返回适当类型的值。以下场景非常好,因为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 用于定义偏函数。它不返回值,但会导致解释器立即退出并显示给定的错误消息。例如

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

    【讨论】:

      猜你喜欢
      • 2022-08-20
      • 2023-03-22
      • 2017-09-13
      • 1970-01-01
      • 2012-11-28
      • 1970-01-01
      • 1970-01-01
      • 2021-10-11
      相关资源
      最近更新 更多