unicorns4re4live
unicorns4re4live

Reputation: 311

How to handle errors outside try/catch?

I have error hiding system from the console using try/catch in many places in my code. Example:

try {
  //code with error
}
catch(e){
  //do nothing
}

Now I'm adding debug mode to my program and I want absolutely all errors to be logged to the console, including those that are handled by the above construction. The easiest way is to add some debugPrint func, where DEBUG env var will be checked, inside every catch, but I'm searching for the shortest way. I tried to add error event listener to window, but this doesn't work. Are there any similar solutions?

Upvotes: 1

Views: 735

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370699

I'd wrap the code to run in a callback passed to a function, and have that function call the callback inside a try/catch, and log if needed:

const runWithCatch = (cb) => {
  try {
    return cb();
  } catch(e) {
    if (debug) {
      console.error(e);
    }
  }
};
runWithCatch(() => {
  // some code that might throw
});

That said, this is pretty weird, and seems like it might be an X/Y problem. Runtime errors should not arise in well-formulated synchronous code; if errors do arise, the code almost certainly should be refactored.

(If you're making asynchronous requests, it's a completely different story, since it's reasonable to expect occasional errors, which aren't due to problems in the code's logic)

Upvotes: 0

Related Questions