ko_ma
ko_ma

Reputation: 1021

Why is return error not working in try-catch? (JavaScript)

In the below code, I'm trying to try-catch.

try-catch Function:

const updateReturnInformation = async () => {
if (state.isLoading) {
  throw new Error('Errrrrror!!!') // <- It is success working
}

dispatch(actionSetLoading(true))
try {
  await updateReturnAPI(...)
} catch (ex) {
  return ex // <- why not working?
} finally {
  dispatch(actionSetLoading(false))
}
}

And, I called this function in another component:

...
try {
  await updateReturnInformation()
  navigation.navigate(Routes.Root.Modal.Confirm, {
    title: 'success!',
    buttons: ['OK'],
  })
} catch (ex) {
  navigation.navigate(Routes.Root.Modal.Confirm, {
    heading: 'Error',
    title: ex,
    buttons: ['OK'],
  })
}
...

I called updateReturnInformation(), But It working only print 'success!' message.

Also, The console.log will still only print a 'success!' message if an error occurs.

Changing the return error of updateReturnInformation () to throw error works fine, but I have to only use return error.

What's wrong?

Upvotes: 0

Views: 173

Answers (2)

Barmar
Barmar

Reputation: 780698

If you have to use return ex, then you have to use the return value in the caller, not catch.

let ex = await updateReturnInformation()
if (ex) {
  navigation.navigate(Routes.Root.Modal.Confirm, {
    heading: 'Error',
    title: ex,
    buttons: ['OK'],
  })
} else {
  navigation.navigate(Routes.Root.Modal.Confirm, {
    title: 'success!',
    buttons: ['OK'],
  })
}

Upvotes: 1

Isac Moura
Isac Moura

Reputation: 6878

The catch() method returns a Promise and deals with rejected cases only. Try using reject(error) and you'll can capture that error upwards.

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch

Upvotes: 2

Related Questions