Jamie Hutber
Jamie Hutber

Reputation: 28076

How to access catch without an error javascript

I may be misinformed, but I have built my try catch on the basis that if there is no error I will run my code inside the catch as so:

try {
  //Something valid
} catch (err) {
  if (!err) {
     //do something
  }
}

Is it possible to catch errors like JSON.parse() that will fail 50% of the time, but you know it will fail half the time, the other half I would like my application not to crash and be able to run as normal?

Upvotes: 0

Views: 58

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370729

You can explicitly throw something at the end of the try block if you want to enter the catch block regardless:

try {
  //Something valid
  throw null;
} catch (err) {
  if (!err) {
     console.log('doing something');
  }
}

Or, perhaps a bit more precisely, check if the err is an instanceof Error in the catch:

try {
  //Something valid
  throw null;
} catch (err) {
  if (!(err instanceof Error)) {
     console.log('doing something');
  }
}

Upvotes: 3

Related Questions