algolia / algoliasearch-client-javascript

⚡️ A fully-featured and blazing-fast JavaScript API client to interact with Algolia.

Home Page:https://www.algolia.com/doc/api-client/javascript/getting-started/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Throw real Errors instead of objects

alexandre-butynski opened this issue · comments

This package has a non standard behavior of throwing objects instead of real JS Errors. As it works approximately in the same way in most cases and these objects are similar to Error (at least, TS is ok with that), there are some edge cases where it messes everything up.

My specific use case is with Sentry, which is not able to handle properly these "errors". Instead of having a proper stack trace, I have the Sentry error Non-Error exception captured and all the informations about the real error are lost.

We do this kind of thing all over the package:

accountCopyIndex.ts

throw createDestinationIndiceExistsError()

createDestinationIndiceExistsError.ts

export function createDestinationIndiceExistsError(): Error {
  return {
    name: 'DestinationIndiceAlreadyExistsError',
    message: 'Destination indice already exists.',
  };
}

I propose instead to either throw a basic Error with the message...

export function createDestinationIndiceExistsError(): Error {
  return new Error('DestinationIndiceAlreadyExistsError');
}

Or even to create custom error objects

class AlgoliaDestinationIndiceAlreadyExistsError extends Error {
  constructor(message) {
    super(message);
    this.name = 'AlgoliaDestinationIndiceAlreadyExistsError';
  }
}

export function createDestinationIndiceExistsError(): Error {
  return new AlgoliaDestinationIndiceAlreadyExistsError('Destination indice already exists.');
}

I even think that this helper methods are not necessary and that custom errors could be thrown directly. For instance, the custom message is useless in this case.

I can open a PR with a proof of concept if you think it's a good idea. I would also be glad to hear your ideas about the right implementation.

I agree that we should return real errors, but changing this could be a breaking change if anyone relies on the type or the keys of the object now. @shortcuts, in v5 we are throwing real errors right?

I agree that it can be considered as a breaking change. Looks good to me if it's fixed in the next major release 👍

Hi, i would like to work on this issue, as i have good knowledge of throwing proper errors. So i will be able to handle it properly.