Hi need to create a table on DynamoDB. The problem is, if it exists createTable
response is an error. How do i avoid that. Because I throw a notification when error occurs, but in this case, I don't want to.
I don't want to compare the error code because ResourceInUseException
is too vague for it. Also, I don't think sending a describe table request first is really a proper solution.
Is there any way to createIfNotExists
?
Since you don't like describeTable() then I guess that listTables() is your only option, e.g.
const tableName = // ...
const tablePromise = dynamodb.listTables({})
.promise()
.then((data) => {
const exists = data.TableNames
.filter(name => {
return name === tableName;
})
.length > 0;
if (exists) {
return Promise.resolve();
}
else {
const params = {
TableName: tableName,
// more params
};
return dynamodb.createTable(params).promise();
}
});
Note, if you have more than 100 tables, the result will be paged and you must call listTables()
repeatedly, see ExclusiveStartTableName
and LastEvaluatedTableName
in the api docs for details.
One other possible solution could be to check the err.code and err.message. The "err.message" gives you the exact reason.
if (err.code === "ResourceInUseException" && err.message === "Cannot create preexisting table") {
console.log("message ====>" + err.message);
} else {
console.error("Unable to create table. Error JSON:", JSON.stringify(err, null, 2));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With