【问题标题】:Terminate nodejs aws lambda function in a .then or .catch function在 .then 或 .catch 函数中终止 nodejs aws lambda 函数
【发布时间】:2020-09-19 23:08:52
【问题描述】:

考虑以下用 nodejs 编写的 AWS lambda 函数。

export const handler: APIGatewayProxyHandler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
  var file;

  await getFile()
    .then((filedata): void => {
      file = filedata;
    }).catch((e): void => {
      < Return error response and stop execution >
    });

  await saveFile(file)
    .then((result): void => {

    }).catch((e): void => {
      < Return error response and stop execution >
    });
  return {statusCode: 200};
};

如果 getFile 失败,我希望 lambda 函数只返回错误并停止执行。

我无法从 .catch 语句返回响应,因为它位于错误的范围内。

我可以用 try/catch 包围整个处理程序,并从 .catch 语句中抛出一个错误,如下所示:

try {
  await getFile()
    .then((filedata): void => {
      file = filedata;
    }).catch((e): void => {
      throw new Error("Error getFile");
    });

  await saveFile(file)
    .catch((e): void => {
      throw new Error("Error saveFile");
    });
  return {statusCode: 200, body: "success"};
} catch (error) {
  return {statusCode: 500, body: error.message};
}

...但我认为有更好的方法?

你会怎么做?

感谢您的帮助!

【问题讨论】:

    标签: javascript node.js typescript amazon-web-services aws-lambda


    【解决方案1】:

    您可以将整个流程编码到 Promise 链中,然后返回整个链,而不是 awaiting 解决承诺然后返回值。承诺的履行值(解决或拒绝)将返回给用户。

    所以你的代码看起来像:

    export const handler: APIGatewayProxyHandler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
        return getFile()
            .then((filedata) : void => {
                return saveFile(filedata);
            })
            .then((result) : void => {
                return {statusCode: 200};
            })
            .catch((e) : void => {
                return {statusCode: 500, message: e}; // or whatever error
            })
    }
    

    【讨论】:

      【解决方案2】:

      如果您可以使用await,您可以选择不使用then(),因此您可以将getFile 部分重写为类似以下内容:

      try {
        file = await getFile():
      } catch(e) {
        < Return error response and stop execution >
      };
      

      【讨论】:

      • 我用我的 try/catch-version 更新了我的问题。我只是在寻找一种更好的方法来做到这一点。
      猜你喜欢
      • 2021-12-12
      • 2018-01-05
      • 1970-01-01
      • 2019-04-08
      • 2016-05-27
      • 1970-01-01
      • 2019-08-15
      • 2017-09-05
      • 1970-01-01
      相关资源
      最近更新 更多