15

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:

  1. Don't use object destructuring

  2. Don't handle the exception

  3. Scope the destructed to the try block

Is it possible to achieve object destructuring and handle an exception?

Chiru
  • 3,661
  • 1
  • 20
  • 30
kyle
  • 2,563
  • 6
  • 22
  • 37

1 Answers1

25

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.

dave
  • 62,300
  • 5
  • 72
  • 93
  • Thank you this is exactly what I was looking for, I couldn't figure out the right way to phrase the question so I wasn't getting good results back. Thanks! – kyle May 03 '18 at 23:29
  • The official doc doesn't mention this, but would I be correct in assuming we need to do the same thing for array destructuring? I'm getting an error when trying to do the same thing with array destructuring and this seemed to solve it but wanted to confirm it's the correct way. – starmandeluxe May 29 '19 at 03:37
  • Damn that was a cool fix! Thanks! – thinklinux Sep 20 '19 at 12:57