将数据传递给 step 函数 catch

Passing data to step function catch

我在 AWS 上使用步进函数。考虑由 lambda 组成的状态机:

"StartAt": "Metadata",
              "States": {
                    "Metadata": {
                    "Type": "Task",
                    "Resource": "${metadataArn}",
                    "Next": "StoreMetadata",
                    "Retry" : [
                            {
                                "ErrorEquals": [ "States.All" ],
                                "IntervalSeconds": 2,
                                "MaxAttempts": 3
                            }
                    ],
                    "Catch": [
                        {
                            "ErrorEquals": [ "States.All" ],
                            "Next": "ErrorHandler"
                        }
                    ]
                  } ...
                      ...

如何将特定数据传递给 "ErrorHandler"。比如失败的步骤,可能是一条数据。我正在使用 nodejs,但可以推断到任何运行时。

例如,在节点中我们可能有一个 lambda,其中:

module.exports.handler = async input => {
  const ids = JSON.parse(input).ids
  // try to read in data for ids.
  // read fails / throws exception
}

如何让错误处理程序获取 ID 数组,以便将它们标记为失败?如果这个 "ErrorHandler" 是多个步骤的陷阱,我怎么才能知道哪些步骤失败了?

我找到了答案,您可以使用 ResultPath 将原始输入连同错误一起传递。我想我会在所有输入中将步骤作为 属性 包括在内,这样我就可以知道哪个步骤失败了。有关解释,请参阅 docs。要实现这一点,您只需像这样添加 ResultPath 属性:

"Catch": [
  {
    "ErrorEquals": [ "States.All" ],
    "Next": "ErrorHandler"
    "ResultPath": "$.error"
  }
]

我想添加到@Zachscs 的回答中,你在 "Type": "Map" 上执行 "Catch" 时需要小心,因为这是执行“ResultPath”:“$.error”,将抛出:

Unable to apply step "error" to input [...]

这是有道理的,因为输入是一个数组。您可以通过向这样的错误添加一个简单的从零开始的索引来解决它:

"Type": "Map",
"Next": "Finish",
"Catch": [
  {
    "ErrorEquals": [ "States.All" ],
    "Next": "ErrorHandler",
    "Comment": "Note the $[0] down below",
    "ResultPath": "$[0].error"
  }
]

这会将其附加到数组的第二个索引 $[1].error

对于那些使用 AWS CDK 创建步骤函数的人:

yourTask.addCatch(sendFailureNotify, {
  resultPath: '$.error'
});

其中 sendFailureNotify 是您的 lambda。道具 resultPath? 是您设置 $.error

的地方
/**
 * Error handler details.
 */
export interface CatchProps {
    /**
     * Errors to recover from by going to the given state.
     *
     * A list of error strings to retry, which can be either predefined errors
     * (for example Errors.NoChoiceMatched) or a self-defined error.
     *
     * @default All errors
     */
    readonly errors?: string[];
    /**
     * JSONPath expression to indicate where to inject the error data.
     *
     * May also be the special value DISCARD, which will cause the error
     * data to be discarded.
     *
     * @default $
     */
    readonly resultPath?: string;
}