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

Fetch错误捕获未达预期:如何避免代码流程中断?

问题:Fetch捕获错误后流程仍终止,如何维持正常流程?

我用fetch实现JSON文件加载功能,参考方案捕获错误(我的场景中文件不存在属于正常情况)。

使用的代码如下:

fetch(l_Real_Reference).then(
    response => {
        if (response.ok) {
        return response.json(); } 

        throw new Error('Could not load file (there is no file)');
    })
    .catch((error) => {
        console.log("Catched error: " + error)
        return ;
      })
      
.then(data => {
    if (p_What == "Master_Index") {
        G_All_Albums = JSON.parse(JSON.stringify(data)) ;
        Populate_Albums_List() ;
    }
})

当加载不存在的文件时,控制台错误截图如下:
错误截图

可见catch已触发,但代码流程仍被终止,请问需修改哪部分代码才能维持代码正常流程不中断?


解决方案

问题核心:catch返回undefined后,后续then仍会执行,但此时data为undefined,执行JSON.parse(JSON.stringify(data))会抛出新错误,导致流程终止。

方案1:在后续then中先校验data有效性

fetch(l_Real_Reference).then(
    response => {
        if (response.ok) {
            return response.json(); 
        } 
        throw new Error('Could not load file (there is no file)');
    })
    .catch((error) => {
        console.log("Catched error: " + error);
        return null; // 明确返回null替代undefined,便于后续判断
    })
    .then(data => {
        // 仅当data有效时才执行业务逻辑
        if (data && p_What == "Master_Index") {
            // 可以简化深拷贝写法,比如对象用G_All_Albums = {...data},数组用[...data]
            G_All_Albums = JSON.parse(JSON.stringify(data));
            Populate_Albums_List();
        }
    })

方案2:将业务逻辑移至成功分支,避免错误进入后续流程

fetch(l_Real_Reference).then(
    response => {
        if (response.ok) {
            // 文件加载成功后才执行业务逻辑
            return response.json().then(data => {
                if (p_What == "Master_Index") {
                    G_All_Albums = JSON.parse(JSON.stringify(data));
                    Populate_Albums_List();
                }
            });
        } 
        throw new Error('Could not load file (there is no file)');
    })
    .catch((error) => {
        console.log("Catched error: " + error);
    })

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 20:46:12