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

146
Visualizações
Is there a way to force a function to error globally in JavaScript?

I've run into a situation wherein it might be beneficial to throw an error wherever a particular function is called in a JavaScript program. By which, I don't mean a reference to the function, but any and all references to the function, i.e., the function itself.


let doThing = ()=>console.log("Hello, world!");

// refer to the thing doThing refers to
let a = doThing;

// change what doThing refers to
doThing = ()=>{throw new Error()}; // This won't work for my use case

// "Hello, world!"
a(); // Because a still points to the working function

let b = a;

// kill what a points to
killFunctionSymbol(a); // Instead, I want something like this

// After which, everything fails...
a(); // Error
b(); // Error

I've read elsewhere that it's impossible to mutate the body of a function. But, in my case, I'm not sure I need to mutate the body. I just need the call to error. Is there any way I can achieve this? Is there some way I can alter the prototype such that it always breaks?

about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

I think what you want is a Proxy. I have to say I'm always on the lookout to use proxies so this is a perfect use case.

Here is a very basic implementation of a proxy that hijacks the call to a function based on some external value

const doThing = (arg1, arg2) => `Hello World! ${arg1} ${arg2}`;

let killSwitch = false;

const handler = {
  apply: function(target, thisArg, argumentsList) {
    if (killSwitch) {
      throw new Error('Kill switch engaged');
    }

    return target(...argumentsList);
  }
};

const regular = doThing;
const withProxy = new Proxy(doThing, handler);

console.log(regular('foo1', 'bar1'));
console.log(withProxy('foo2', 'bar2'));

killSwitch = true;
console.log(withProxy('foo3', 'bar3'));

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy

Hope this helps.

about 4 years ago · Santiago Gelvez 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