try-and-catch不会捕获promise错误



下面是我的代码

try {
const connect_to_database = async () =>{
const sequelize = new Sequelize('testing','sugumar','mypassward',{
host:'127.0.0.1',
dialect:'mysql'
})
await sequelize.authenticate()
}
connect_to_database()
} catch(e) {
}

我不想抛出任何错误,但它在终端中抛出错误

部分错误是

(node:25701) UnhandledPromiseRejectionWarning: SequelizeAccessDeniedError: Access denied for user 'sugumar'@'localhost' (using password: YES)
at Promise.tap.then.catch.err (/home/user/Desktop/sugumar/testing/node_modules/sequelize/lib/dialects/mysql/connection-manager.js:125:19)
at tryCatcher (/home/user/Desktop/sugumar/testing/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/home/user/Desktop/sugumar/testing/node_modules/bluebird/js/release/promise.js:547:31)

您必须等待像await connect_to_database()这样的promise函数调用。

connect_to_database函数是async,这意味着它返回一个promise

您可以试试这段代码,看看它是否能像我目前只在Sequelize上工作一样工作。

const sequelize=new Sequelize('database','root','password',{host:'localhost',dialect:'mysql',logging:false});
sequelize.authenticate().then(function(err) 
{
console.log('Connection has been established successfully.');
}).catch(function(err)
{
});
const connect_to_database = async () => {
try {
const sequelize = new Sequelize('testing', 'sugumar', 'mypassward', {
host: '127.0.0.1',
dialect: 'mysql'
})
await sequelize.authenticate();
} catch (error) {
}
}
connect_to_database();

我应该只为等待调用放入try-catch

最新更新