1 回答

TA貢獻1847條經驗 獲得超7個贊
在考慮 try/catch 塊時,您走的是正確的道路,但請注意我也使用了“catch”。通常(也許這甚至是強制執行的,我不記得了)你需要 catch 塊和 try。
所以你的函數看起來像這樣:
function async myFirstTryCatch() {
try {
// Make your request in the try block
await requestCall();
} catch(error){
// Hey, my http call returned an error
// Deal with the error here. Maybe show a toast, validate a form
// Anything you need to not break the code and have good UX
console.log(error)
}
}
按照同樣的思路,您可以讓每個函數處理自己的 try/catch,或者在您的應用函數中控制它,以防某些鏈必須繼續/停止相互依賴。
function apply() {
try {
firstCall();
functionThatRequiresFirstCalltoSucceed();
} catch (error){
//Will catch if either firstCall or functionThatRequiresFirstCalltoSucceed fail
console.log(error)
}
functionThatIndependsFromTheResultAbove();
}
我希望這會幫助你建立關于 JS 錯誤處理的想法 :)
重要說明 如果您的代碼進入 catch 塊,它將認為錯誤已被處理并且不會傳播!這是一個例子
function functionThatThrowsError(){
try{
throw new Error('Example Error!');
} catch (error) {
// Error has been dealt with
console.log(error) // Returns "Example Error"
// throw error; <--- Throw the error in the catch block if you need t to propagate
}
}
function wontCatchError() {
try {
functionThatThrowsError();
} catch (error) {
// THE CODE WILL NOT ENTER THE CATCH BLOCK
// SINCE THE ERROR WAS CAUGHT IN THE FUNCTION ITSELF.
// If you need to catch here as well, make sure to throw the error
// in the catch block of the 'functionThatThrowsError'
console.log(error)
}
}
添加回答
舉報