reactjs – try-catch statement in React JSX

reactjs – try-catch statement in React JSX

React JSX

It looks like a TypeScript style. Just use try{ } catch(e) { console.error(e); } would be fine.

Take a look at MDN, and dont forget that JSX is just a syntax sugar for React.createElement.

JSX – a faster, safer, easier JavaScript

The link you mentioned is not react React JSX, but a whole new thing call DeNA JSX.

Take a look at this issue in DeNA JSX, and this PR.

In JSX or JavaScript you can write it like this

try {
console.log(window.device.version) 
} catch (e) {
console.log(Error)
}

If you are using TypeScript your previous code should work

Hope that helps

reactjs – try-catch statement in React JSX

The try statement lets you test a block of code for errors.

The catch statement lets you handle the error.

The throw statement lets you create custom errors.

The final statement lets you execute code, after try and catch, regardless of the result.


The basic concept goes like this:

  try {
   // Block of code to try
}
catch(err) {
    // Block of code to handle errors
}

So, lets now make a scenario where an error would occur:

// It will try to run the task, but it will fail

try {
  eval(console.log(Hello world));  // Just add the missing quote at the end of world word and it will pass :) 
}

// So, here is where we catch the error and display it to the user

catch(error) { 
  console.error(error);
  
  // expected output:
  // message: Uncaught SyntaxError: Invalid or unexpected token
  // Note - error messages will vary depending on browser
}

Leave a Reply

Your email address will not be published.