Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AggregateError cannot be used with instanceof #392

Closed
convers39 opened this issue Mar 26, 2024 · 3 comments
Closed

AggregateError cannot be used with instanceof #392

convers39 opened this issue Mar 26, 2024 · 3 comments

Comments

@convers39
Copy link

convers39 commented Mar 26, 2024

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
Copy link
Author

convers39 commented Mar 27, 2024

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
Copy link

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
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants