javascript forEach管理例外

时间:2018-07-30 11:47:06

标签: javascript testing foreach error-handling throw

我有一个forEach循环,用于在将数据推入数组之前检查是否存在条件:

allow(id, perm, arr) {
  const data = { "userId": id, "permissionId": perm };

  arr.forEach(key => {
    if (id !== key.userId) {
      throw new Error('id does not exists');
    } else {
      if (perm === key.permissionId) {
        throw new Error('perm exists in this id');
      } else {
        arr.push(data);
      }
    }
  });
}

原始数组arr如下:

[{"userId": 1,"permissionId": 1},
 {"userId": 2,"permissionId": 1},
 {"userId": 3,"permissionId": 0},
 {"userId": 4,"permissionId": 0}]

如果我使用console.log()可以正常工作,但是当我抛出错误时,执行将停止,但是如何在不停止循环的情况下管理异常?

2 个答案:

答案 0 :(得分:2)

throw旨在停止循环/代码调用。如果要在循环后抛出这些错误,则可以将所有错误推入数组并将它们抛出到末尾:

allow(id, perm, arr) {
  const data = { "userId": id, "permissionId": perm };
  const errors = [];

  arr.forEach(key => {
    if (id !== key.userId) {
      errors.push('id does not exists');
    } else {
      if (perm === key.permissionId) {
        errors.push('perm exists in this id');
      } else {
        arr.push(data);
      }
    }
  });

  if (errors.length > 0) {
    throw new Error(errors.join());
  }
}

答案 1 :(得分:0)

尝试捕获您抛出的异常。

https://www.w3schools.com/js/js_errors.asp