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

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

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 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