DEV Community

Luka Vidaković
Luka Vidaković

Posted on

Shortwire the async/await's catch

Handling exceptions in the async/await functions can become really bothersome. You can have multiple await calls inside a function for which you need to handle exceptions separately. This requires either wrapping every await call inside its own try/catch block, or using a single try/catch and trying to handle multiple exception types inside a single catch block. Either way, not too pretty. Especially if you want a way to easily resume execution only if some of the async calls fail. But, if you remember that what's awaited for is a simple Promise, things become much more flexible. Rejects can be handled by using well known .catch callback:

async function fetchUserPosts(userId) {
  const user = await fetchUser(userId).catch(() => null)
  return user
    ? await fetchPosts(user.postIds)
    : []
}
Enter fullscreen mode Exit fullscreen mode

We chain fetchUser's original Promise by using .catch method. catch returns another Promise that resolves with either a fetched user, or null if any error occurred during the fetchUser call. By eliminating the possibility of an exception on the first line, onwards we only need to think of 2 possible cases:

  1. there is user data
  2. there is no user data :)

This is a very simplified example of how to elegantly skip non-critical exceptions without breaking up your code into a few loosely connected chunks. This is however not a suggested approach for general async/await error handling.

Top comments (0)