从 if 块中抛出错误,也会导致其他语句的执行

时间:2021-06-27 18:20:49

标签: javascript validation try-catch

我正在编写代码来验证表单的字段。因此,我编写了一个名为 validateFields 的函数来执行此操作。因此,如果所有字段都正确,则该函数将返回 true 否则返回 false。 validateFields 函数在另一个名为 saveForm 的函数中调用。 saveForm 函数的目的是仅在validateFields 返回true 时才保存数据。 saveForm 已经在 try 块中执行了另一个承诺回调,如果承诺失败,则返回一个错误。 我想要实现的是,如果validateFields 返回false,那么我想在saveForm 函数中抛出一个错误。

// this function is present in another file say validation.js
function validateForm(){
//some logic to validate which returns true or false;
}
 
//this function is present in another file say saveForm.js, the structure of saveForm function is as follows
function saveForm(){
 var isFormValid = validation.validateForm(); //validateForm function invoked
try{
//some existing logic to send the saved form
}catch(error){
console.log(error)
}

}

现在,如果 isFormValid 为 false,那么我不想执行 try 块中的现有逻辑,而是抛出一个错误,指出表单验证失败。我尝试按以下方式进行,但失败了

function saveForm(){
try{
 var isFormValid = validation.validateForm(); //validateForm function invoked
try{
//some existing logic to send the saved form
}catch(error){
console.log(error)
}catch(error){
console.log("Validation failed error");
}

}
}

我只想执行外部 catch 块,但相反,我从两个 catch 块中获取消息,所以任何人都可以帮助我如何放置 isValidForm 逻辑,以便我只得到验证失败错误?< /p>

1 个答案:

答案 0 :(得分:0)

在每个 catch or finally 之后应该有一个 try

在您的逻辑中,最后一次捕获应该在第一次尝试之外,以捕获其错误,即使这样也没有 if 语句来检查 isFormValid

试试这个逻辑:

function saveForm() {
  var isFormValid = validation.validateForm(); //validateForm function
  try {
    if (!isFormValid) {
      throw "Form is invalid";
    } else {
      try {
        //some existing logic to send the saved form
        console.log("form save logic");
        // throw error if something goes wrong. Only for test purpose
        throw "Error while saving";
      } catch (error) {
        console.log(error);
      }
    }
  } catch (error) {
    console.log(error);
  }
}

OR 这个,哪个 IMO 更具可读性

function saveForm() {
  var isFormValid = validation.validateForm(); //validateForm function
  if (isFormValid) {
    try {
      //some existing logic to send the saved form
      console.log("form save logic");
      // throw error if something goes wrong. Only for test purpose
      throw "Error while saving";
    } catch (error) {
      console.log(error);
    }
  } else {
      try{
        throw "Form is invalid";
      }
      catch(error){
          console.log(error);
      }
  }
}