sodiray / radash

Functional utility library - modern, simple, typed, powerful
https://radash-docs.vercel.app
MIT License
4.1k stars 160 forks source link

AggregateError cannot be used with `instanceof` #392

Closed convers39 closed 1 month ago

convers39 commented 5 months ago

As per the native AggregateError examples:

try {
  throw new AggregateError([new Error("some error")], "Hello");
} catch (e) {
  console.log(e instanceof AggregateError); // true
  console.log(e.message); // "Hello"
  console.log(e.name); // "AggregateError"
  console.log(e.errors); // [ Error: "some error" ]
}

We can use instanceof to check if the error is an AggregateError.

Currently instanceof does not catch the patched version:

https://github.com/rayepps/radash/blob/master/src/async.ts#L88-L104

/**
 * Support for the built-in AggregateError
 * is still new. Node < 15 doesn't have it
 * so patching here.
 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError#browser_compatibility
 */
export class AggregateError extends Error {
  errors: Error[]
  constructor(errors: Error[] = []) {
    super()
    const name = errors.find(e => e.name)?.name ?? ''
    this.name = `AggregateError(${name}...)`
    this.message = `AggregateError with ${errors.length} errors`
    this.stack = errors.find(e => e.stack)?.stack ?? this.stack
    this.errors = errors
  }
}

This could be done by adding:

export class AggregateError extends Error {
  static {
    this.prototype.name = 'AggregateError';
  }
  // ...
}

But not sure if the current implementation is intended, or if is there any recommended walkaround to catch an AggregateError.

convers39 commented 5 months ago

my current walkaround with a type guard

export const isAggregateError = (error: unknown): error is AggregateError => {
  return (
    error instanceof Error &&
    error.name.startsWith('AggregateError') &&
    'errors' in error &&
    Array.isArray(error.errors)
  );
};
aleclarson commented 1 month ago

Hello @convers39. Over at the Radashi fork, we've fixed this issue by using globalThis.AggregateError when it's available (see #116). You can use it today by installing radashi@beta. (An official release is pending)

https://github.com/radashi-org/radashi

convers39 commented 1 month ago

@aleclarson Thank you for following up! Will migrate to Radashi then!