0

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?

1
  • You're not assigning the return value of updateReturnInformation() to anything. How can you tell that return ex is not working? Commented Jul 9, 2019 at 2:29

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for reference!
1

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'],
  })
}

2 Comments

Thank you for your solution!
But, it does not working if (state.isLoading) { throw new Error('Errrrrror!!!') }.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.