【问题标题】:Why does catch not return the error in this case? [duplicate]为什么在这种情况下 catch 不返回错误? [复制]
【发布时间】:2021-01-31 15:49:42
【问题描述】:

刚接触 Fetch API 的初学者。我正在尝试console.log 当有人试图获取一个不存在但它不起作用的文件时出现的错误消息。它只是。谁能解释一下我哪里出错了。

document.getElementById('button1').addEventListener('click', getText);

//getText function
function getText() {
    //fetching file that doesn't exist to produce the error
    fetch('text.text')
    .then(function(response){
        return response.text();
    })
    .then(function(data){
        console.log(data);
    })//what's supposed to happen when the error is caught
    .catch(function(error){
        console.log(error);
    })
}

【问题讨论】:

  • 当您在发回 404 页面的服务器上运行此程序时,从技术上讲,获取请求并没有失败。但是,您可以查看response.status === 404
  • @ChrisG - 是的。我见过的最近最糟糕的 API 决策之一。 :-)

标签: javascript try-catch


【解决方案1】:

你遇到了fetch footgun (这是我贫血的小博客上的帖子)fetch 不会拒绝它对 HTTP 错误的承诺,只有 网络 em> 错误。您必须自己检查 HTTP 错误(如 404)。我通常为此使用包装函数,但这里是直接使用fetch 的方法:

function getText() {
    fetch('text.text')
    .then(function(response){
        if (!response.ok) {                                    // ***
            throw new Error("HTTP error " + response.status);  // ***
        }                                                      // ***
        return response.text();
    })
    .then(function(data){
        console.log(data);
    })
    .catch(function(error){
        console.log(error);
    })
}

FWIW,我倾向于使用的包装器是:

class FetchError extends Error {
    constructor(response) {
        super(`HTTP error ${response.status}`);
        this.response = response;
    }
}

function fetchJSON(...args) {
    fetch(...args)
    .then(response => {
        if (!response.ok) {
            throw new FetchError(response);
        }
        return response.json();
    });
}

function fetchText(...args) {
    fetch(...args)
    .then(response => {
        if (!response.ok) {
            throw new FetchError(response);
        }
        return response.text();
    });
}

 // ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-31
    • 1970-01-01
    • 1970-01-01
    • 2016-03-02
    • 2014-09-12
    • 2018-04-26
    • 2018-05-21
    • 2021-12-03
    相关资源
    最近更新 更多