In javascript, is it possible to perform object destructing while still handling an exception? For example this is what I would ideally like to be able to do the syntax isn't valid
let body;
let err;
try {
{ body } = await networkRequest(...); // invalid syntax
} catch (e) {
err = e;
}
From what I can tell the options are to either:
Don't use object destructuring
Don't handle the exception
Scope the destructed to the try block
Is it possible to achieve object destructuring and handle an exception?
You're getting a parsing error because, without a declaration, object destructure assignment looks like it could be a block on the left side and the ES2015 spec says it must be parsed as a block.
You can fix this by surrounding with parentheses so the engine knows it's an expression:
let body;
let err;
try {
({ body } = { body: 'test' })
} catch (e) {
err = e;
}
console.log(body);
You can read about this exact problem here.
The round braces ( ... ) around the assignment statement is required syntax when using object literal destructuring assignment without a declaration.
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