EricSmekens / jsep

JavaScript Expression Parser
http://ericsmekens.github.io/jsep/
MIT License
827 stars 133 forks source link

Consider using SyntaxError instead of Error in throwError #254

Open jdanyow opened 1 year ago

jdanyow commented 1 year ago

A more specific exception might make it easier for jsep(...) callers to be confident the error is something that could be displayed to a user to help them correct their expression vs any other unexpected exception.

I realize the index and description properties could be used instead, however something more TypeScript friendly like extending SyntaxError could be a further improvement for folks catching these exceptions. If you agree, I'd love to open a PR.

export class JsepError extends SyntaxError {
  constructor(
    public readonly description: string;
    public readonly index: number;
  ) {
    super(`${description} at character ${index}`);
    this.name = this.constructor.name;
    if (typeof Error.captureStackTrace === 'function') {
      Error.captureStackTrace(this, this.constructor);
    }
  }
}
    /**
     * throw error at index of the expression
     * @param {string} message
     * @throws
     */
    throwError(message) {
-       const error = new Error(message + ' at character ' + this.index);
-       error.index = this.index;
-       error.description = message;
-       throw error;
+       throw new JsepError(message, this.index);
    }