sra*_*nji 8 javascript error-handling node.js amazon-dynamodb nestjs
我正在尝试将一些数据插入 dynamodb,正如预期的那样,我得到了一个ConditionalCheckFailedException. 因此,我试图仅针对该场景捕获该异常,除此之外,我想为所有其他错误抛出服务器错误。但是要添加类型,我无法ConditionalCheckFailedException在 aws-sdk 中找到。
这就是我想要做的。
// 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')
}
}
Run Code Online (Sandbox Code Playgroud)
Kim*_*ern 13
您可以使用以下保护来检查错误:
if (e.code === 'ConditionalCheckFailedException') {
Run Code Online (Sandbox Code Playgroud)
请注意,instanceof仅适用于类,不适用于接口。所以即使你有类型,如果它是一个接口你也不能使用它,因为它依赖于某些原型检查。使用该err.code属性更安全。
当您使用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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3214 次 |
| 最近记录: |