0

For error handling in async/await in JavaScript, normally I see people use try catch to handle this.

e.g.


async function apiCall() {
  throw new Error('failed')
}

async function run() {
  try {
    const response = await apiCall() 
    if(response.status === 'success') {
      console.log('success!')
    }
  } catch(e) {
    console.log('e', e)
  }
}

I never really liked try-catch block then I recently happened to know there is another way to handle it without relying on try-catch block

async function run2() {
  const response = await apiCall().catch(console.log)
  if(!response) return
  if(response.status === 'success') {
    console.log('success!')
  }
}

But the downside is that it will continue executing the following lines even if there is an error so we have to manually return in the case of an error.

I wonder which way is better or in which cases one is preferred over the other?

Joji
  • 4,703
  • 7
  • 41
  • 86
  • Another downside of the second approach is that if `apiCall()` returns `undefined` in a normal case, it won't be distinguishable from the `undefined` that your `.catch()` handler returns. Sometimes that works, but sometimes it doesn't. – Bergi Mar 28 '21 at 22:11
  • thanks that is a good point! – Joji Mar 28 '21 at 22:15

0 Answers0