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

137
Views
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 answers
Answer question

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