Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object destructuring and handling exceptions [duplicate]

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?

like image 698
kyle Avatar asked May 03 '18 22:05

kyle


1 Answers

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.

like image 132
dave Avatar answered Oct 01 '22 18:10

dave