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

如何在单个catch块中捕获多层嵌套异步函数的所有错误

问题根本原因

现有代码中内层异步请求返回的 Promise 没有接入外层的 Promise 调用链,属于独立的未处理 Promise 实例,因此它抛出的错误无法向外冒泡到外层的 catch 块。


方案1:Promise.all 包装并行任务(推荐,无性能损耗)

如果你不需要等待内层任务执行完成再走后续逻辑,只需要把所有并行执行的内层异步任务都放入Promise.all,外层then返回这个Promise.all实例即可。所有内层任务依然并行执行,性能和原有写法完全一致,任何一个任务抛出的错误都会直接触发外层 catch:

Bungie.Get('/Platform/Destiny2/Manifest/').then((ResponseText)=>{
    // 所有并行异步任务统一放入数组
    return Promise.all([
        Bungie.Get('/Platform/Destiny2/Mnifest/').then((ResponseText)=>{
            console.log('Success')
        }),
        // 可追加任意数量的并行异步任务,无需单独加catch
        // Bungie.Get('其他接口地址').then(...)
    ])
}).catch((error)=>{
    // 外层、所有内层异步任务的错误都会被捕获到此处
    doSomethingWithError(error)
});

方案2:封装统一请求 wrapper(适合分散调用场景)

如果你的内层异步任务是分散在多处、不方便统一放到同一个Promise.all中,可以封装一个内置统一错误处理的请求方法,后续所有请求直接调用该方法即可,无需重复编写 catch 逻辑:

// 封装统一请求工具,内置错误处理
const bungieGet = (url, successHandler) => {
  return Bungie.Get(url)
    .then(res => successHandler?.(res))
    .catch(err => doSomethingWithError(err))
}

// 业务代码调用示例
Bungie.Get('/Platform/Destiny2/Manifest/').then((ResponseText)=>{
    // 直接调用封装好的方法,不用单独写catch
    bungieGet('/Platform/Destiny2/Mnifest/', (ResponseText) => {
        console.log('Success')
    })
}).catch((error)=>{
    doSomethingWithError(error)
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 21:00:07