You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何调用函数中的catch代码块始终无法执行?

问题分析与解决办法

你的main函数里的catch块不执行,核心原因是**second函数内部已经捕获了抛出的错误,并且将错误作为返回值返回,而非重新抛出错误**。这导致await second()得到的是一个正常的返回结果(即使是Error对象),不会触发上层的catch逻辑。

解决方案1:在second函数的catch块中重新抛出错误

如果second函数需要先处理错误再让上层捕获,就在catch块末尾添加throw error,把错误传递到上层:

async function main() {
  try {
    console.log('jatin')
    const hello = await second()
    console.log(hello)
    console.log('yes boy')
  } catch (e) {
    console.log('cm')
    console.log(e)
  }
}

async function second() {
  try {
    console.log('in second')
    throw new Error()
  } catch (error) {
    console.log('trial')
    console.log(error)
    // 重新抛出错误,让上层main函数的catch捕获
    throw error
  }
}

main()

解决方案2:移除second函数内部的try/catch

如果second函数不需要自行处理错误,直接去掉内部的try/catch,让错误自然向上层传递:

async function main() {
  try {
    console.log('jatin')
    const hello = await second()
    console.log(hello)
    console.log('yes boy')
  } catch (e) {
    console.log('cm')
    console.log(e)
  }
}

async function second() {
  console.log('in second')
  throw new Error()
}

main()

以上两种修改后,main函数的catch块都会正常执行指定的语句。

内容的提问来源于stack exchange,提问作者Jatin Mehrotra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 19:17:23