简体   繁体   English

在JavaScript中抛出多个异常

[英]Throw multiple exceptions in JavaScript

I'm wondering if there is a way to throw multiple errors and catch all of them in JavaScript. 我想知道是否有办法抛出多个错误并在JavaScript中捕获所有错误。

I'm looking for specific fields, and when I find a missing one I would like to throw an error. 我正在寻找特定的字段,当我找到一个丢失的字段时,我想抛出一个错误。

The problem is that if I throw a single error, like: 问题是如果我抛出一个错误,比如:

throw "you are missing field: " xxxxxx

I'm not telling the user all of the other fields which he/she is missing. 我没有告诉用户他/她缺少的所有其他字段。

I would also not like to combine everything into a single string, since the error message might be too long. 我也不想将所有内容组合成一个字符串,因为错误消息可能太长。

Any ideas? 有任何想法吗?

Thanks. 谢谢。

你可以抛出任何类型的对象,你不仅限于字符串,所以你不妨将你的错误消息收集到一个对象中,如果出现任何错误,最后抛出它。

You create your own type of Error that holds the list of missing fields: 您创建自己的Error类型,其中包含缺少字段的列表:

class MissingFieldsError extends Error {
  constructor(fields, ...params) {
    super(...params);
    this.fields_ = fields;
  }

  getMissingFields() {
    return this.fields_;
  }
}

To use it, you can gather all of the missing fields first and then throw an instance of MissingFieldsError . 要使用它,您可以先收集所有缺少的字段,然后抛出MissingFieldsError的实例。 Assuming you have some sort of array of Field instances, the code should look like this: 假设您有某种Field实例数组,代码应如下所示:

const missingFields = fields
    .filter((field) => field.isMissing())
    .map((field) => field.getName());

if (missingFields.length > 0) {
  throw new MissingFieldsError(
      missingFields, 'Some required fields are missing.');
}

If you prefer, you can even have separate Error s thrown, collect them and then throw the MissingFieldsError : 如果您愿意,您甚至可以抛出单独的Error ,收集它们然后抛出MissingFieldsError

const missingFields = [];

fields.forEach((field) => {
  try {
    const value = field.getValue();
    // Process the field's value.

    // Could be just field.validate();
  } catch (e) {
    missingFields.push(field.getName());
  }
});

if (missingFields.length > 0) {
  throw new MissingFieldsError(
      missingFields, 'Some required fields are missing.');
}

Hey so currently dealing with an issue related to this. 嘿所以目前处理与此相关的问题。 Just wanted to add a couple thoughts. 只是想添加一些想法。

throw allows you to throw any expression and it will generate an exception which will kick into the catch clause if it exists with the value populated as the parameter (typically an Error ). throw允许你抛出任何表达式,它会产生一个异常,如果它存在并且填充了作为参数的值(通常是一个Error ),它将进入catch子句。 This is user-defined though so you can essentially throw whatever you want. 这是用户定义的,所以你可以扔掉你想要的任何东西。

So if you really wanted to throw an array of exceptions, you totally can. 所以,如果你真的想抛出一系列例外,你完全可以。 ie something like this 即这样的事情

try {
  var errors = [];
  for (let i=0; i<10; i++) {
    errors.push(new Error('Here is a special exception'));
  }

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

} catch(e) {
    for (let i=0; i<e.length; i++) {
      console.log(e[i]);
    }
}

I think some things to be aware of 我想有些事情需要注意

  • can your function throw different types? 你的函数能抛出不同的类型吗? If you can throw arrays, numbers, exceptions, any other expressions, you'll need to handle all those cases. 如果你可以抛出数组,数字,异常,任何其他表达式,你将需要处理所有这些情况。 Generally people will move this into their own error handler, so you'll need to handle collections in this case 通常人们会将其移动到自己的错误处理程序中,因此在这种情况下您需要处理集合
  • be careful of nested try/catch statements. 小心嵌套的try / catch语句。 You would normally need to be aware of this but throwing it out there (haha!) anyways for sanity purposes. 你通常需要注意这一点,但扔掉它(哈哈!)无论如何都是出于理智目的。
  • When handling async code where errors can get populated into the array at different times, make sure to utilize await and Promise.all before going through (unless you don't mind missing out on exceptions). 处理异步代码时,错误可以在不同的时间填充到数组中,请确保在Promise.all之前使用awaitPromise.all (除非您不介意错过异常)。

In terms of how good/bad practice it is, I honestly couldn't find much about it. 就实践的好坏而言,老实说,我找不到多少。 I would say tread lightly and understand if your use case really needs this. 我会轻描淡写,明白你的用例是否真的需要这个。 Sometimes it's helpful but you may not need to process the entire array of exceptions. 有时它很有用,但您可能不需要处理整个异常数组。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM