Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

349
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda