Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

345
Views
How to throw an error when using a property of an object

I would like JS to throw an error when a object is used that isn't properly instantiated.

I have tried like this already:

var person = function () { throw new Error('Person not instantiated!'); };
...
var x = person.age; //should throw an error when person isn't overwritten

but it doesn't throw an error like I want it (only if I would type person();).

The problem here is that I give the object into numerious methods and don't want to make error handling for all occurrences. Is there a way to throw an error when reading a property of an object?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Is there a way to throw an error when reading a property of an object?

Yes you can patch the property getter with a function throwing an error

var person = {};
Object.defineProperty(person, 'age', {
  get: function () { throw new Error('Person not instantiated!') }, 
});

var x = person.age;

Or you can also replace the object with a Proxy that will allow you to override a getter for all properties:

var person = new Proxy({}, {
  get(target, name) {
    throw new Error('Person not instantiated!');
  }
});

var x = person.age;
var y = person.name;

But all of this is an anti-pattern. Is something that I would suggest against.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!