function abc() {
try {
setTimeout(() => {
console.log('inside timeout!!');
throw new Error('Somehting went wrong!!');
}, 1000);
} catch (err) {
console.log('Gonna catch it here and throw is again', err);
throw new Error(err);
}
}
try {
abc();
} catch (err) {
console.log('err caught here', err);
}
如何捕获错误?我应该在哪里用try / catch包装代码? 即使可以保证,catch块为什么不能捕获错误。
async function abc() {
setTimeout(() => {
throw new Error();
}, 1000);
}
try {
abc();
} catch (err) {
console.log('err is ', err);
}
答案 0 :(得分:1)
将其包装为Promise:
function abc(simulateError) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (simulateError)
reject('Something went wrong')
else
resolve('foo')
})
})
}
// Call it using then/catch to handle result or errors...
abc(true).then(result => {
console.log(result)
})
.catch(err => {
console.log(err)
})
// or await on the Promise, which allows using try/catch.
;(async () => {
try {
const result = await abc(true)
console.log(result)
} catch (err) {
console.log(err)
}
})()