Fix "Unexpected token 'if'" — conditional catch clauses on V8
SyntaxError: Unexpected token 'if'
Why it happens
Rhino supported Mozilla's conditional catch clauses: several catch (e if …) blocks after one try. They were never standard, so V8 refuses to parse the file.
The fix
Use one catch and branch inside it. Re-throw anything you didn't handle — that is what Rhino did when no clause matched.
// Rhino
try {
var data = JSON.parse(cache);
} catch (e if e instanceof SyntaxError) {
data = {};
} catch (e if e.message.indexOf('quota') >= 0) {
Utilities.sleep(1000);
}
// V8
try {
var data = JSON.parse(cache);
} catch (e) {
if (e instanceof SyntaxError) {
data = {};
} else if (e.message.indexOf('quota') >= 0) {
Utilities.sleep(1000);
} else {
throw e;
}
}
Gotchas
- Forgetting the final
else { throw e; }swallows errors Rhino would have propagated. - If clauses used different variable names (
catch (err if …)thencatch (e)), alias them inside the block.
How V8Shift handles it
The whole chain — including a trailing unconditional catch — is merged into a single catch (e) { if … else if … else … } automatically.