In JavaScript's Async/Await feature, it is common to declare variables that await an expression outside of the try...catch block to ensure their accessibility later. However, it is a best practice to minimize business logic within the try body to handle exceptions effectively.
try { const createdUser = await this.User.create(userInfo); console.log(createdUser); // Business logic goes here } catch (error) { console.error(error); // from creation or business logic }
This approach ensures that all exceptions, including those from business logic, are captured.
If you wish to catch errors only from the promise, consider the following options:
Declare the variable outside the block and handle errors through branching:
let createdUser; try { createdUser = await this.User.create(userInfo); } catch (error) { console.error(error); // from creation } if (createdUser) { // User was created successfully console.log(createdUser); // Business logic goes here }
Check the type of the caught exception and handle accordingly:
try { const createdUser = await this.User.create(userInfo); // User was successfully created console.log(createdUser); // Business logic goes here } catch (error) { if (error instanceof CreationError) { console.error(error); // from creation } else { throw error; } }
An alternative to try...catch that offers simplicity and correctness is using .then() callbacks:
await this.User.create(userInfo).then( (createdUser) => { // User was created successfully console.log(createdUser); // Business logic goes here }, (error) => { console.error(error); // from creation } );
Consider the advantages and drawbacks of each option based on your specific requirements.
The above is the detailed content of How to Correctly Use Try...Catch with Async/Await in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!