Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try-catch statement in React JSX

Tags:

reactjs

jsx

According to the JSX reference, this is what a try-catch statement must look like

try {
  statement*
} [catch (varname : type) {
  statement*
}]* [finally {
  statement*
}]

I tried the following

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

Which results in the error

Module build failed: SyntaxError: Unexpected token, expected ) (11:15)

9  |     try {
10 |       console.log(window.device.version)
11 |     } catch (e : TypeError) {
   |                ^
12 |       console.log('Error')
13 |     }
14 |     return (

What is the correct way to use a try-catch statement in JSX then ?

like image 787
MetaTom Avatar asked Aug 14 '18 03:08

MetaTom


People also ask

What is catch in React JS?

catch statement can be used to catch JavaScript errors in React components. This is because the try... catch statement only works for imperative code, as opposed to the declarative code we have in components.

How do you use try catch?

The “try… It works like this: First, the code in try {...} is executed. If there were no errors, then catch (err) is ignored: the execution reaches the end of try and goes on, skipping catch . If an error occurs, then the try execution is stopped, and control flows to the beginning of catch (err) .

What is the difference between try catch block and error boundaries?

catch deals with imperative code while error boundaries*deal with declarative code. Imperative programming is how you do something and declarative programming is what you do. With error boundary, if there is an error, you can trigger a fallback UI; whereas, with try… catch, you can catch errors in your code.

What is finally in try catch?

The try statement defines the code block to run (to try). The catch statement defines a code block to handle any error. The finally statement defines a code block to run regardless of the result. The throw statement defines a custom error. Both catch and finally are optional, but you must use one of them.


1 Answers

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 don't 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.

like image 199
NoobTW Avatar answered Jan 03 '23 21:01

NoobTW