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

我仍在学习这门语言,而且我非常想知道当一个动作需要执行一系列函数时,确保所有函数都将执行或不执行的正确方法是什么。例如,我可能有一个调用某些 apply() 函数的 HTML 按钮:


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 {} 并检查参数是否有错误等,但看起来我无法预见一切,我只需要一些方法来告诉代码“确保您可以执行所有功能,在如果出现任何错误,根本不要做任何事情”。请告知这里可以做什么?


catspeake
浏览 106回答 1
1回答

aluckdog

在考虑 try/catch 块时,您走的是正确的道路,但请注意我也使用了“catch”。通常(也许这甚至是强制执行的,我不记得了)你需要 catch 块和 try。所以你的函数看起来像这样:function async myFirstTryCatch() {&nbsp; &nbsp;try {&nbsp; &nbsp; &nbsp;// Make your request in the try block&nbsp; &nbsp; &nbsp;await requestCall();&nbsp; &nbsp;} catch(error){&nbsp; &nbsp; &nbsp; // Hey, my http call returned an error&nbsp; &nbsp; &nbsp; // Deal with the error here. Maybe show a toast, validate a form&nbsp; &nbsp; &nbsp; // Anything you need to not break the code and have good UX&nbsp; &nbsp; &nbsp; console.log(error)&nbsp; &nbsp;}}按照同样的思路,您可以让每个函数处理自己的 try/catch,或者在您的应用函数中控制它,以防某些链必须继续/停止相互依赖。&nbsp; &nbsp; function apply() {&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;firstCall();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;functionThatRequiresFirstCalltoSucceed();&nbsp; &nbsp; &nbsp; &nbsp; } catch (error){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //Will catch if either firstCall or&nbsp; functionThatRequiresFirstCalltoSucceed fail&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(error)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; functionThatIndependsFromTheResultAbove();&nbsp; &nbsp; }我希望这会帮助你建立关于 JS 错误处理的想法 :)重要说明 如果您的代码进入 catch 块,它将认为错误已被处理并且不会传播!这是一个例子function functionThatThrowsError(){&nbsp; try{&nbsp; &nbsp; throw new Error('Example Error!');&nbsp; } catch (error) {&nbsp; &nbsp; &nbsp;// Error has been dealt with&nbsp; &nbsp; &nbsp;console.log(error) // Returns "Example Error"&nbsp; &nbsp; &nbsp;// throw error;&nbsp; &nbsp;<--- Throw the error in the catch block if you need t to propagate&nbsp; }}&nbsp;function wontCatchError() {&nbsp; &nbsp;try {&nbsp; &nbsp; &nbsp; functionThatThrowsError();&nbsp; &nbsp;} catch (error) {&nbsp; &nbsp; &nbsp; // THE CODE WILL NOT ENTER THE CATCH BLOCK&nbsp; &nbsp; &nbsp; // SINCE THE ERROR WAS CAUGHT IN THE FUNCTION ITSELF.&nbsp; &nbsp; &nbsp; // If you need to catch here as well, make sure to throw the error&nbsp; &nbsp; &nbsp; // in the catch block of the 'functionThatThrowsError'&nbsp; &nbsp; &nbsp; console.log(error)&nbsp; &nbsp;}&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript