0

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?

1
  • Umm weird question. Why not, use a flag and after the try-catch check that flag and avoid this weird logic. Commented Mar 14, 2019 at 0:56

1 Answer 1

3

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');
  }
}

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.