Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

353
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda