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

标签 javascript function error-handling try-catch

我仍在学习该语言,我很想知道什么是确保执行一个功能需要执行一系列功能时,要么执行所有功能,要么不执行所有功能的正确方法。例如,我可能有一个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”。通常情况下(我什至不记得,甚至是强制执行的),您都需要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或控制您的apply函数中的内容,以防某些链条必须继续/停止相互依赖的情况。
    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)
   }
 }

关于javascript - 消除由于不可预见的错误而导致的一组功能的不完整执行(JavaScript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64508723/

相关文章:

c++ - 编译器错误的单元测试

python - 分段故障?我没有看到任何错误...

javascript - 正则表达式替换为 Javascript

javascript - React setState 不影响 Children

java - 如何使用 Java 中的函数和方法循环读取字符串

c - 如何将字符串传递给C中的函数

javascript - 将函数作为 AngularJS 中的选择值传递

javascript - <li>标签的数值位于哪里?

javascript - 函数内定义的变量导致引用错误 : not defined