0

I am defining a class. I want an error to be thrown when the user tries to access a property that does not exist.

How can this be done?

  • Why exactly do you want to do this? You may have [an XY Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Using a dictionary may make more sense, but couldn't you just use a normal try catch? – cocomac May 16 '22 at 21:23
  • What if the user simply mis spelled the property? I want an error to be thrown in that situation. – Bear Bile Farming is Torture May 16 '22 at 21:32
  • Oh... sorry, I mis-read your question. I thought you wanted to _not_ throw an error. But you could maybe make a function to check for `undefined` as a result and throw an error if it is undefined. That could work – cocomac May 16 '22 at 21:37
  • also: [Is there a way to catch an attempt to access a non existant property or method?](https://stackoverflow.com/questions/2666602/is-there-a-way-to-catch-an-attempt-to-access-a-non-existant-property-or-method) and pasting your question title into google also yields: [Fire an error when Object property does not exists](https://stackoverflow.com/questions/32213991/fire-an-error-when-object-property-does-not-exists#:~:text=Suppose%20you%20are%20calling%20to,throw%20Error%20instead%20of%20undefined.&text=You%20can%20use%20use%20strict%20either.) – pilchard May 16 '22 at 21:39

1 Answers1

-2

You can throw your own object, and associate an Error instance with it:

try{ throw {
  foo: "bar",
  error: new Error()
};

The throw statement is not picky, but the Error() constructor is. Of course, if you throw something that's not an Error, it's only useful if the catching environment expects it to be whatever you throw.

Having the Error object as part of your custom thrown value is useful because a constructed Error instance has (in supporting browsers, which currently seems to be essentially all of them) an associated stack trace.

I got this idea from an other similar question.

Sujai Dev
  • 1
  • 2