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

调用端错误处理程序未捕获异常问题排查

问题:Async函数异常未被调用端try/catch捕获

问题场景

createSchedule是一个发起POST请求的async函数,内部未做错误处理。调用端在自定义事件回调中通过try/catch包裹该函数调用,但触发401权限错误或变量引用错误时,catch块的日志始终未打印。

原调用端代码

Schedule.onCustomEvent('Schedule:created', async function () {
  const schedule = this;
  try {
    return createSchedule(schedule);
  } catch (e) {
    console.log(`Schedule Error: Did not create schedule for ${schedule.name} : ${schedule._id}`);
    console.error(e);
  }
});

原createSchedule函数

const createSchedule = async (schedule) => {
  // headers 和 url 已在外部定义

  const { data } = await axios( {
    method: 'post',
    url,
    headers,
    data: {
      schedule: {
        name: schedule.name,        
        timezone: schedule.getTimezone() || 'US/Eastern'
      },
      enable_sis_reactivation: true,
    }
  })
  return data;
}

原因分析

核心问题是调用端未用await等待createSchedule执行完成:

  • createSchedule是async函数,调用后立即返回一个Promise对象
  • 原代码中直接return createSchedule(schedule),try块会同步执行完毕并返回该Promise,此时Promise的拒绝状态(错误)不会被当前的try/catch捕获
  • 部分事件发射器不会处理async回调返回的Promise的拒绝,导致错误被静默吞掉

解决方案

在try块中添加await,等待异步函数执行完成,这样Promise的拒绝状态会被try/catch捕获:

修正后的调用端代码

Schedule.onCustomEvent('Schedule:created', async function () {
  const schedule = this;
  try {
    // 添加await,等待异步操作完成
    return await createSchedule(schedule);
  } catch (e) {
    console.log(`Schedule Error: Did not create schedule for ${schedule.name} : ${schedule._id}`);
    console.error(e);
  }
});

补充说明

  • createSchedule内部的await axios(...)会在请求失败时抛出错误(axios请求失败会返回rejected状态的Promise)
  • 调用端添加await后,该错误会被传递到外层的try/catch块,触发日志打印
  • 如果事件发射器不支持处理async回调的返回值,可根据需求在catch块处理完错误后,选择重新抛出错误(确保错误被上层感知)或直接忽略

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 21:50:38