这是一些代码:
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
is meant to be used with Promises .如果您拒绝 promise ,那么您可以捕获
错误,如果您解决 promise ,它将成为函数的返回值。
async function helloWorld () {
return new Promise(function(resolve, reject){
reject('error')
});
}
try {
await helloWorld();
} catch (e) {
console.log('Error occurred', e);
}
关于javascript - 如何使用 async/await 捕获抛出的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33562284/