Home >Web Front-end >JS Tutorial >How to Correctly Use Try...Catch with Async/Await in JavaScript?

How to Correctly Use Try...Catch with Async/Await in JavaScript?

DDD
DDDOriginal
2024-12-29 04:37:10421browse

How to Correctly Use Try...Catch with Async/Await in JavaScript?

Correct Try...Catch Syntax Using Async/Await

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.

Best Practices

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.

Alternative Options for Handling Promise Errors

If you wish to catch errors only from the promise, consider the following options:

1. Declare Variable Outside and Handle Errors

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
}

2. Test Caught Exception Type

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;
  }
}

3. Utilize .then() Callbacks

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn