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 ?
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.
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) .
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.
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.
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With