【问题标题】:Throwing multiple exceptions inside of a function在函数内抛出多个异常
【发布时间】:2021-10-28 03:13:34
【问题描述】:

我正在实现一个引发错误的表单验证函数。这些异常会冒泡并在我的应用程序中的更高级别上进行管理:

this.form.inputs.forEach(input => {
  if (input.required && !input.value) {
    throw new AppError({ customMessage: new Notification(notificationTypes.Error, `${input.label} not filled`)});
  }
})

事情是抛出异常停止函数执行,所以我只能捕捉到第一个错误。

有什么建议吗?我的想法不多了:(

【问题讨论】:

  • 不是立即抛出,而是收集所有异常,只有在函数结束后才抛出它们的集合?

标签: javascript exception error-handling throw


【解决方案1】:

如果你想继续检查,你不需要抛出异常。相反,有一个指示问题的对象数组,并用该数组抛出一个异常:

const errors = [];
this.form.inputs.forEach(input => {
    if (input.required && !input.value) {
        errors.push({ customMessage: new Notification(notificationTypes.Error, `${input.label} not filled`)});
    }
});
if (errors.length) {
    throw new AppError(errors);
}

【讨论】:

  • 我明白了。所以抛出异常会停止函数的执行;就像 return 一样。我一直在寻找一段时间,但我还没有找到任何关于这种行为的参考,但很高兴知道它。谢谢!
  • @SergioMartín - 是的,就是这样。
【解决方案2】:

可能是这样的

const errs = this.form.inputs
  .map(input => {
    if (input.required && !input.value) {
      return new AppError({ customMessage: new Notification(notificationTypes.Error, `${input.label} not filled`)});
    }
  })
  .filter(err => err !== undefined)

【讨论】:

    【解决方案3】:

    只要抛出异常,该线程内的执行就会中止,通量控制将转到调用线程。

    如果您想为所有控件返回验证消息,可以将它们添加到 for 循环内的数组中,然后返回这些值(或在 for 循环外抛出异常)。

    【讨论】:

      【解决方案4】:

      这可以解决你的问题

      this.form.inputs.forEach(input => {
       try {
        if (input.required && !input.value) {
          throw new AppError({ customMessage: new Notification(notificationTypes.Error, `${input.label} not filled`)});
        }
       }
      catch (e) {
           console.log(e)
      } 
      })
      

      请试试这个并回复评论

      【讨论】:

      • 每次投球都会进入接球。因为异常被捕获它不会冒泡,所以我的错误处理程序永远不会收到它。感谢您尝试!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-27
      • 2017-08-25
      • 2015-05-15
      • 1970-01-01
      • 2023-03-19
      • 2015-08-26
      相关资源
      最近更新 更多