Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to throw an error when an attribute is changed?

Tags:

javascript

I want to make sure an error gets thrown when an attribute of an object gets changed outside the class. Here's how I tried to do it:

class Example {
  constructor(index) {
    this.index = index;

    Object.defineProperty(this, 'index', {
      set() {
        throw new AssertionError("can't set attribute");
      }
    });
  }
}

class AssertionError extends Error {
  constructor(message) {
    super();
    this.name = "AssertionError";
    this.message = message;
  }
}


let example = new Example(5);
console.log(example.index); //prints undefined instead of 5
example.index = 10; // I want to throw an AssertionError here

The error gets thrown just like I wanted, but the index value is undefined. I still want to be able to change the attribute inside of the class, but I want to prevent the attribute from changing outside of the class.

like image 854
zjeffer Avatar asked Jun 10 '19 13:06

zjeffer


People also ask

How do you throw an error in a function?

To indicate that a function, method, or initializer can throw an error, you write the throws keyword in the function's declaration after its parameters. A function marked with throws is called a throwing function. If the function specifies a return type, you write the throws keyword before the return arrow ( -> ).

Does throwing a new error stop execution?

throw new Error('something went wrong') — will create an instance of an Error in JavaScript and stop the execution of your script, unless you do something with the Error.

What does throw new error do?

throw new Error("My error"): this returns you an object where you can access the error value from the message property.


1 Answers

You redefine the property with the call to defineProperty. You should give it a getter:

Object.defineProperty(this, 'index', {
  get() { return index; },
  set() {
    throw new AssertionError("can't set attribute");
  }
});

Any given property name can only be used once; a property has to either be a plain property or a property with getter/setter functions.

like image 58
Pointy Avatar answered Sep 19 '22 05:09

Pointy