【问题标题】:Why is return error not working in try-catch? (JavaScript)为什么返回错误在 try-catch 中不起作用? (JavaScript)
【发布时间】:2019-07-09 02:16:21
【问题描述】:

在下面的代码中,我正在尝试捕捉。

try-catch 功能:

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))
}
}

而且,我在另一个组件中调用了这个函数:

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

我调用了 updateReturnInformation(),但它只能打印“成功!”消息。

此外,console.log 仍然只会打印“成功!”发生错误时的消息。

将 updateReturnInformation () 的 return error 更改为 throw error 可以正常工作,但我只能使用 return error

怎么了?

【问题讨论】:

  • 您没有将updateReturnInformation() 的返回值分配给任何东西。你怎么知道return ex 不起作用?

标签: javascript


【解决方案1】:

catch() 方法返回一个 Promise 并且只处理被拒绝的情况。尝试使用reject(error),您可以向上捕获该错误。

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

【讨论】:

  • 感谢您的参考!
【解决方案2】:

如果你必须使用return ex,那么你必须使用调用者中的返回值,而不是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'],
  })
}

【讨论】:

  • 感谢您的解决方案!
  • 但是,它不起作用if (state.isLoading) { throw new Error('Errrrrror!!!') }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-18
  • 1970-01-01
  • 2017-06-12
  • 1970-01-01
  • 1970-01-01
  • 2015-07-11
  • 1970-01-01
相关资源
最近更新 更多