【问题标题】:Failed fetch() in REACT without statusText nor json body. How to get extra info on error?REACT 中的 fetch() 失败,没有 statusText 也没有 json 正文。如何获取有关错误的额外信息?
【发布时间】:2019-05-28 06:35:32
【问题描述】:

我试图寻找这个问题的答案,但我没有找到它,如果它是重复的,对不起

我有一个简单的应用程序,在 REACT 和 java 后端有一个网站,该网站从后端获取一个 json 并用它显示一些东西。 问题是当后端返回错误消息时,例如带有以下正文的 503 http 响应:

{"status":503,"name":"InternalServerErrorException","message":"3rd party service is not available"}

问题是,fetch() 仅在 response.ok 为 false 时获取有关 http 状态码的信息。我无法获得 statusMessage 或从后端返回的 json(我尝试使用 response.body 但它是一个锁定的流,似乎我无法读取它)

获取代码为:

handleErrors = (response) => {
    if (!response.ok) {
        throw Error(response.statusText);
    }
    return response;
};

submit = (form) => {
    this.setState({ response: null, loading: true, error: false });
    fetch(this.getUrl(form))
        .then(this.handleErrors)
        .then((clusterList) => {
            return clusterList.json();
        })
        .then(clusterJson => this.setState({response: clusterJson, loading: false}))
        .catch((e) => {
        console.log(e);
        this.setState({ error: true, loading: false, errorM: e.message});
    });
};

我尝试了一些在其他帖子和教程中找到的方法,但似乎没有任何效果。而且我不能将每条错误消息都变成不同的错误代码,即“错误输入”有很多错误,这些错误在消息上有所不同。

有什么方法可以得到错误的额外信息吗?

【问题讨论】:

  • 您是否尝试过重新抛出整个错误响应?如果您只是传递收到的所有内容,这似乎是为自己设置最大错误数据提取的最佳方式。
  • 这无济于事,我需要向用户打印出问题的消息。我得到的错误只有状态值
  • 好吧,我的意思是,如果您可以传递尽可能多的错误响应,那么以后推导出错误会更容易。我有时会使用一些 API 返回完全无用的错误,无论如何我都不得不提供一些通用错误。 TBH,从可用性的角度来看,您可能希望用户友好的错误而不是神秘的错误代码......
  • 是的,但我在网站的最后一行。这就是我需要阅读我收到的错误并为用户很好地打印出来的地方。

标签: javascript reactjs


【解决方案1】:

如果response.status 不是2xx,则从response.body 获取错误。

【讨论】:

    【解决方案2】:

    Welp,我找到了。它必须在另一个问题的某个地方,但不是太明显(甚至不是问题的答案,只是一个答案) 有答案的帖子是Retrieve data from a ReadableStream object?

    问题是,我试图将正文作为流读取或返回内容,例如 response.ok == true 时。我不知道为什么其他地方列出的所有其他方法都不起作用。令我惊讶的是,这个答案也不适用于提出这个问题的人。

    最后的答案是:

    handleErrors = (response) => {
        if (!response.ok) {
            response.json().then(body => this.setState({errorMessage: body.message}));
            throw Error(response);
        }
        return response;
    };
    
    submit = (form) => {
        this.setState({ response: null, loading: true, error: false });
        fetch(this.getUrl(form))
            .then(this.handleErrors)
            .then((clusterList) => {
                return clusterList.json();
            })
            .then(clusterJson => this.setState({response: clusterJson, loading: false}))
            .catch((e) => {
            this.setState({ error: true, loading: false});
        });
    };
    

    新年快乐!

    【讨论】:

      猜你喜欢
      • 2018-12-06
      • 2017-04-08
      • 2010-11-11
      • 1970-01-01
      • 1970-01-01
      • 2020-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多