【问题标题】:Capturing full fetch errors [duplicate]捕获完整的提取错误[重复]
【发布时间】:2019-11-26 19:06:45
【问题描述】:

我有一个获取请求:

fetch(url, {

}.then(function(resp))
    // do something
}.catch(err => {
    console.log(err);
}

我的问题涉及获取err 的整个堆栈跟踪。例如,这里是真正的错误信息:

Access to fetch at 'https://www.google.com/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

太好了。这是一个有用的消息。但是,console.log(err) 会打印出TypeError: Failed to fetch。这是一个非常无用的错误消息。有什么方法可以捕获记录在控制台中的整个消息(即var message = //the full errorerr.stack 似乎不是一个函数,err.message 返回同样无用的Failed to fetch 消息

【问题讨论】:

  • .then() 中抛出一个console.log(JSON.stringify(resp) );,看看它会返回什么?
  • @Snowmonkey 没有出现
  • 你在 repl.it、codepen 或 jsfiddle 上有这个吗?
  • @Snowmonkey 给你jsfiddle.net/a490qkvd

标签: javascript fetch


【解决方案1】:

一般情况下,在使用fetch 时,您希望使用response.ok 属性,这起初有点令人困惑。 This 是一篇非常好的文章,它包含了这个或多或少你想做的例子:

fetch("http://httpstat.us/500")
    .then(function(response) {
        if (!response.ok) {
            throw Error(response.statusText);
        }
        return response;
    }).then(function(response) {
        console.log("ok");
    }).catch(function(error) {
        console.log(error);
    });

也就是说,如果您最终遇到 CORS 错误,您仍然会收到 TypeError: Failed to fetch,因为他们没有给您一个很好的错误代码(例如 404),他们只是取消了 HTTP 请求

【讨论】:

  • 所以这意味着没有办法从 Fetch 访问完整的错误消息?这似乎是一个很大的可用性问题
  • 有一种方法可以从 Fetch 访问完整的错误消息。在我的回答中。但是,这不适用于 CORS 错误,因为它们不是 HTTP 错误
  • ...有没有办法访问 CORS 或其他网络错误?
猜你喜欢
  • 1970-01-01
  • 2012-07-04
  • 2018-08-13
  • 1970-01-01
  • 2010-11-22
  • 2018-08-02
  • 1970-01-01
  • 2017-04-17
  • 2021-02-27
相关资源
最近更新 更多