消除由于不可预见的错误(JavaScript)而导致的一组函数的不完整执行



我仍在学习该语言,我很想知道当一个操作需要执行一系列函数时,什么是确保所有函数都执行或不执行的正确方法。例如,我可能有一个HTML按钮,它调用一些apply((函数:

function apply() {
try {
// Check arguments, choose what exactly to do next through some IFs etc...
}
anotherFunction();
}
function anotherFunction() {
try {
// Request data from DB, process data received, update object variables, etc...
}
yetAnotherFunction();
}
function yetAnotherFunction() {
try {
// Update HTML
}
oneMoreFunction();
}
function oneMoreFunction() {
try {
// Update graph
}
}

因此,这里的问题是,如果流中的任何函数抛出错误,其余函数将不会执行它们应该执行的操作,因此整个Apply过程将因应用了一些更改而中断(假设HTML正在更新(,但其余函数(图(则没有。我很想知道预防这种行为的最佳做法是什么?是的,我正在尽我所能使用try{}和检查参数是否有错误等,但看起来我不能预见一切,我只需要一些方法来告诉代码";确保您可以执行所有的函数,在出现任何错误的情况下,不要做任何事情"。请告知在这里可以做些什么?

在考虑try/catch块时,您选择了正确的路径,但请注意,我也使用了"catch"。通常(也许这是强制的,我记不清了(,你需要在尝试的同时抓住盖帽。

所以你的功能可能看起来像这样:

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)
}
}

最新更新