1

I can declare extended Error class like:

class NotFoundError extends Error {
  constructor (message) {
    super(message)
    this.name = 'NotFoundError' // for log
  }
}

and then evaluate:

if (error instanceof NotFoundError) {
  ...
}

How can I declare many errors dynamically, preferably in ES5 syntax?

declareErrors(['NotFoundError', 'TimeoutError', 'AclError', ...])
Darius
  • 1,060
  • 2
  • 6
  • 17

2 Answers2

2

Easy, use an anonymous class expression and assign it to a global variable:

function declareError(name) {
  window[name] = class extends Error {
    constructor (message) {
      super(message)
      this.name = name;
    }
  }
}
function declareErrors(errors) {
  errors.forEach(declareError);
}
declareErrors(['NotFoundError', 'TimeoutError', 'AclError']);

const error = new AclError("Bad Darius!");
console.log(
    error.name,
    error.message,
    error instanceof Error,
    error instanceof AclError
);
Amadan
  • 191,408
  • 23
  • 240
  • 301
0

Dynamically extending Error in pure ES5, as suggested @Amadan and https://stackoverflow.com/a/43595019/12918181, extending with error class name:

function declareError(name) {
  function CustomError(message, fileName, lineNumber) {
    var instance = new Error(message, fileName, lineNumber);
    Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
    return instance;
  }
  CustomError.prototype = Object.create(Error.prototype, {
    constructor: {
      value: Error,
      enumerable: false,
      writable: true,
      configurable: true
    }
  });
  CustomError.prototype.name = name;
  if (Object.setPrototypeOf){
    Object.setPrototypeOf(CustomError, Error);
  } else {
    CustomError.__proto__ = Error;
  }

  window[name] = CustomError
}
function declareErrors(errors) {
  errors.forEach(declareError);
}
declareErrors(['NotFoundError', 'TimeoutError', 'AclError']);
console.log(new NotFoundError('file: test.txt').stack);

Not perfect, but woks almost as expected

Darius
  • 1,060
  • 2
  • 6
  • 17