javascript forEach 管理异常

javascript forEach manage exceptions

我有一个 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() 一切正常,但是当我抛出错误时执行停止,但是我如何在不停止循环的情况下管理异常?

throw 旨在停止您的 loop/code 调用。如果你想在循环后抛出这些错误,你可以将所有错误推入数组并在最后抛出:

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());
  }
}

尝试捕捉你抛出的异常。

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