#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
4 min read
Question 3 of 62easy

How to handle errors in async/await?

Best practices for error handling with async/await in Node.js.

What You'll Learn

  • Try-catch with async/await
  • Global error handling
  • Express async error handling

Basic Try-Catch

code.jsJavaScript
async function fetchUser(id) {
  try {
    const user = await User.findById(id);
    if (!user) throw new Error('User not found');
    return user;
  } catch (error) {
    console.error('Error:', error.message);
    throw error;
  }
}

Express Async Handler

code.jsJavaScript
// Wrapper to catch async errors
const asyncHandler = (fn) => (req, res, next) => {
  Promise.resolve(fn(req, res, next)).catch(next);
};

// Usage
app.get('/users/:id', asyncHandler(async (req, res) => {
  const user = await User.findById(req.params.id);
  if (!user) {
    const error = new Error('User not found');
    error.statusCode = 404;
    throw error;
  }
  res.json(user);
}));

// Error middleware catches it
app.use((err, req, res, next) => {
  res.status(err.statusCode || 500).json({
    error: err.message
  });
});

Multiple Async Operations

code.jsJavaScript
// Handle multiple promises
async function getData() {
  try {
    const [users, posts] = await Promise.all([
      fetchUsers(),
      fetchPosts()
    ]);
    return { users, posts };
  } catch (error) {
    // Handle any failure
    throw error;
  }
}