Fre*_*one 1 javascript mysql asynchronous node.js es6-promise
我想测试查询不存在的表的异步功能。因此,该错误是有意产生的。
async function getPosts() {
try {
const connection = await dbConnection()
const result = await connection.query('SELECT * FROM x')
await connection.release()
console.log(result)
}
catch(ex) {
throw new Error(ex)
}
}
Run Code Online (Sandbox Code Playgroud)
当我调用该函数时:
UnhandledPromiseRejectionWarning:错误:错误:ER_NO_SUCH_TABLE:表'test.x'不存在。
你能告诉我为什么吗?
您得到的UnhandledPromiseRejectionWarning
原因是您没有在其中添加.catch
处理程序getPosts()
getPosts()
.then(console.log)
.catch(console.error); // You're missing this
Run Code Online (Sandbox Code Playgroud)
或使用 async/await
try {
const posts = await getPosts();
console.log(posts);
} catch(e) { // Missing this
console.error(e);
}
Run Code Online (Sandbox Code Playgroud)
如果您不做任何修改就再次抛出该错误,则无需try/catch
在getPosts
函数上添加。只是让它冒泡,然后在调用时处理错误,getPosts()
如上所示。
async function getPosts() {
const connection = await dbConnection()
const result = await connection.query('SELECT * FROM x')
await connection.release()
return result;
}
Run Code Online (Sandbox Code Playgroud)
关于当前错误,您正在尝试对不存在的表执行查询。
您可以通过以下问题了解更多信息:什么是未处理的承诺拒绝?
嗨,过去的我自己!
您的控制台显示了一个未处理的错误,因为在您的 catch 块中,您(我曾经)愚蠢地重新抛出了一个 JavaScript 错误。
只需将其throw new Error(ex)
从您的文件中删除catch
并使用一些错误处理逻辑进行更改即可。
归档时间: |
|
查看次数: |
2084 次 |
最近记录: |