【问题标题】:where to find all the exception classes in AWS-SDK for dynamodb in NodeJS typescript?在哪里可以找到 AWS-SDK for dynamodb 在 NodeJS 打字稿中的所有异常类?
【发布时间】:2019-08-27 12:21:28
【问题描述】:

我正在尝试将一些数据插入 dynamodb,并且正如预期的那样,我得到了 ConditionalCheckFailedException。因此,我试图仅针对该场景捕获该异常,除此之外,我想为所有其他错误引发服务器错误。 但是要添加类型,我无法在 aws-sdk 中找到 ConditionalCheckFailedException

这就是我想要做的。

// where to import this from   
try {
   await AWS.putItem(params).promise()
} catch (e) {
  if (e instanceof ConditionalCheckFailedException) { // unable to find this exception type in AWS SDK
    throw new Error('create error')
  } else {
    throw new Error('server error')
  }
}

【问题讨论】:

    标签: javascript node.js error-handling amazon-dynamodb nestjs


    【解决方案1】:

    更新:aws-sdk v3

    自版本 v3 起,属性名称已更改为 name

    if (e.name === 'ConditionalCheckFailedException') {
    

    旧帖:aws-sdk v2

    您可以改为使用以下防护来检查错误:

    if (e.code === 'ConditionalCheckFailedException') {
    

    请注意,instanceof 仅适用于类,不适用于接口。所以即使你有类型,如果它是一个接口,你也不能使用它,因为它依赖于某些原型检查。使用err.code 属性更安全。

    【讨论】:

      【解决方案2】:

      当您使用aws-sdk v3 时,错误没有code 属性。相反,你想检查error.name

      例如:

      import { S3Client, GetObjectCommand } from '@aws-sdk/client-s3';
      
      const key = 'myKey.json';
      const s3Client = new S3Client({});
      const command = new GetObjectCommand({
          Bucket: 'bucketName',
          Key: key
      });
      
      try {
          const response = await s3Client.send(command);
      } catch (error) {
          if (error.name === 'NoSuchKey') {
              console.warning(`My key="${key}" was not found.`);
          } else {
              throw error;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-02-12
        • 2021-01-28
        • 1970-01-01
        • 1970-01-01
        • 2017-10-08
        • 1970-01-01
        相关资源
        最近更新 更多