聚合错误AggregateError

635 阅读1分钟

如今网络的一个大主题是并发性,这导致异步完成任务。 在这样做的时候,可能会发生多种错误。 与其提供一个通用错误,不如提供大量的错误信息。 AggregateError 错误让开发者在一个单一的Error 中抛出多个错误。 让我们看看它是如何工作的。

为了抛出一个代表多个错误的单一错误,让我们使用AggregateError

const error = new AggregateError([
  new Error('ERROR_11112'),
  new TypeError('First name must be a string'),
  new RangeError('Transaction value must be at least 1'),
  new URIError('User profile link must be https'),
], 'Transaction cannot be processed')

抛出一个AggregateError ,可以得到以下信息。

error instanceof AggregateError // true
error.name // 'AggregateError'
error.message // 'Transaction cannot be processed'
error.errors // The array of errors

在验证多组数据时,AggregateError 是非常有用的;与其一次抛出一个错误,不如把它们归为一个,这是最理想的。AggregateErrorPromise.any 的情况下,会非常有用。 沟通的、富含信息的错误FTW!