[英]How do I catch thrown errors with async / await?
这是一些代码:
import 'babel-polyfill'
async function helloWorld () {
throw new Error ('hi')
}
helloWorld()
我也深入尝试了这个:
import 'babel-polyfill'
async function helloWorld () {
throw new Error ('hi')
}
async function main () {
try {
await helloWorld()
} catch (e) {
throw e
}
}
main()
和:
import 'babel-polyfill'
async function helloWorld () {
throw new Error ('hi')
}
try {
helloWorld()
} catch (e) {
throw e
}
这有效:
import 'babel-polyfill'
async function helloWorld () {
throw new Error('xxx')
}
helloWorld()
.catch(console.log.bind(console))
所以它有点棘手,但是你没有捕获错误的原因是因为,在顶层,整个脚本可以被认为是一个同步函数。 您想要异步捕获的任何内容都需要包装在async
函数中或使用Promises。
例如,这会吞下错误:
async function doIt() {
throw new Error('fail');
}
doIt();
因为它与此相同:
function doIt() {
return Promise.resolve().then(function () {
throw new Error('fail');
});
}
doIt();
在顶层,你应该总是添加一个普通的Promise风格的catch()来确保你的错误得到处理:
async function doIt() {
throw new Error('fail');
}
doIt().catch(console.error.bind(console));
在Node中,还有一个可用于捕获所有Promise错误的进程上的全局unhandledRejection
事件。
async
意味着与Promises一起使用 。 如果您拒绝承诺,那么您可以catch
错误,如果您解决了承诺,那将成为函数的返回值。
async function helloWorld () {
return new Promise(function(resolve, reject){
reject('error')
});
}
try {
await helloWorld();
} catch (e) {
console.log('Error occurred', e);
}
要捕获来自异步 function 的错误,您可以等待错误:
async function helloWorld () {
//THROW AN ERROR FROM AN ASYNC FUNCTION
throw new Error('hi')
}
async function main() {
try {
await helloWorld()
} catch(e) {
//AWAIT THE ERROR WITHIN AN ASYNC FUNCTION
const error = await e
console.log(error)
}
}
main()
或者,您可以等待错误消息:
async function main() {
try {
await helloWorld()
} catch(e) {
//AWAIT JUST THE ERROR MESSAGE
const message = await e.message
console.log(message)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.