【问题标题】:Throwing an error from the if block, results into execution of other statements as well从 if 块中抛出错误,也会导致其他语句的执行
【发布时间】:2021-06-27 18:20:49
【问题描述】:

我正在编写代码来验证表单的字段。因此,我编写了一个函数名称 validateFields 来执行此操作。因此,如果所有字段都正确,则该函数将返回 true,否则返回 false。 validateFields 函数在另一个名为 saveForm 的函数中调用。 saveForm 函数的目的是仅当 validateFields 返回 true 时才保存数据。 saveForm 已经在 try 块中执行了另一个 promise 回调,如果 promise 失败,则返回错误。 我想要实现的是,如果 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 逻辑,以便我只收到验证失败错误?

【问题讨论】:

标签: javascript validation try-catch


【解决方案1】:

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

在您的逻辑中,最后一次捕获应该在第一次尝试之外,以捕获其错误,即使这样也没有 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);
  }
}

或者这个,哪个 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);
      }
  }
}

【讨论】:

  • 谢谢@Danish Aziz
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-05
  • 1970-01-01
  • 2023-02-16
  • 1970-01-01
  • 2020-09-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多