amazonka:捕获满足特定条件的异常

amazonka: catch exceptions that meet certain criteria

我正在使用优秀的 amazonka 库。

我有一个函数需要将 updateItem 转换为 DynamoDB table。更新包括一个条件表达式。

如果更新成功,那么我的函数 returns True(在应用程序 monad 中)。如果更新抛出 ServiceError,其中 ErrorCode 等于 ConditionalCheckFailed,那么我的函数 returns False。所有其他异常都被函数调用者捕获。

换句话说,我希望函数 return True 成功更新到 table,False 否则我想抛出所有异常上面那个是正常的。

我的问题是我不知道如何检查上面的 ErrorCodeServiceError 是否被抛出。

这是我试过的(try来自Control.Monad.Catch和returns m (Either e a),第一列括号中的数字进一步对应错误中的行号下):

[41]    rs <- try $ send $ updateItem "TableName" & uiKey ...blah blah
        case rs of
[47]      Left e  -> if (serviceCode e) == (errorCode "ConditionalCheckFailed")
                     then return False else throwM e
          Right _ -> return True

errorCode 是类型 ErrorCode 的构造函数。 serviceCode是一个lens,把服务代码从错误中拉出来

我也试过用tryJust:

rs <- try' $ send $ updateItem "TableName" & uiKey ...blah blah
where try' = tryJust (\e -> if (serviceCode e) == (errorCode "ConditionalCheckFailed") then Nothing else Just e)

在这两种情况下,我似乎都无法让谓词 if (serviceCode e) == (errorCode "ConditionalCheckFailed") 进行类型检查(我不太了解镜头):

    Couldn't match expected type ‘ServiceError -> f1 ServiceError’
                with actual type ‘ErrorCode’
    Relevant bindings include
      e :: ErrorCode -> f1 ErrorCode
        (bound at src/Foo.hs:47:10)
      rs :: Either (ErrorCode -> f1 ErrorCode) UpdateItemResponse
        (bound at src/Foo.hs:41:3)
    Possible cause: ‘errorCode’ is applied to too many arguments
    In the second argument of ‘(==)’, namely
      ‘(errorCode "ConditionalCheckFailed")’
    In the expression:
      (serviceCode e) == (errorCode "ConditionalCheckFailed")

我怎样才能让这样的东西工作?

您需要使用 amazonka 中预定义的 one of lens' exception handling function along with lens exception。 大致如下:

handling _ConditionalCheckFailedException ({- your handling code goes here -}) $
  do send $ updateItem "TableName" & uiKey ...blah blah

Also amazonka docs