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)
}
}
添加回答
举报