基本上問題是,即使我將導致錯誤的代碼包裝在 try catch 中,錯誤仍然會停止代碼,這是我的代碼。
// snip
try{
// get user using id "does-not-exist", which does not exist
// code stops when fetching user
client.users.fetch('does-not-exist').then(function (user) {
user.send('hello');
});
}catch(err){
console.error('message could not be sent');
}
為什么即使我用 try catch 包裝我的代碼也會停止?
uj5u.com熱心網友回復:
try/catch應該與async/await結合使用。如果要使用同步 then/catch,請使用相應的.catch()回呼。
client.users.fetch('does-not-exist')
.then(function (user) {
user.send('hello');
})
.catch(err => /* error handle */);
如果你想忽略錯誤無效它
.catch(_ => null);
異步等待的外觀
try {
const user = await client.users.fetch('does-not-exist')
} catch (err) {
/* Handle Error */
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/408523.html
標籤:
