反应获取引发问题

时间:2018-07-18 01:17:00

标签: javascript reactjs fetch

在这里与新手联系。我在使用react fetch api并尝试引发自定义错误时遇到问题。我有一个在localhost:8080上运行的rest api端点。从那以后,我已经关闭了该流程(模仿停机服务),我想抛出一个更具描述性的错误,而不是标准的“无法获取”错误。似乎代码拒绝了我的上述错误,并使用默认的提取错误。有没有办法覆盖这个?

fetchData() {
fetch('http://localhost:8080/locales/all')
  .then(function(response) {
    if (response.ok) {
      return response.json();
    }
    throw Error('Oops, looks like the service is down :-(');
  })
  .then(parsedJSON => {
    this.setState({
      locales: parsedJSON.content,
      isLoading:false
    });
  }).catch(error => {
    this.setState({
      error: error.message,
      isLoading:false
    });
    console.log(error.message); // results in Failed to fetch
});

1 个答案:

答案 0 :(得分:1)

问题在于,最初的thread_time调用可以使用fetch对象来解决,但是如果Response完全失败,它将根本无法解决,并将直接进入fetch。如果将其放在代码中,这将很清楚:

catch

当您看不到fetch('http://localhost:8080/locales/all') .then(function(response) { console.log('got a response'); 时,将无法got a response内的throw自定义错误消息。

.then

相反,您可以在function fetchData() { fetch('http://localhost:8080/locales/all') .then(function(response) { console.log('got a response'); if (response.ok) { return response.json(); } throw new Error('Oops, looks like the service is down :-('); }).catch(error => { console.log(error.message); }); } fetchData();本身内部更改错误消息:

catch

}).catch(error => {
  if (error.message === 'Failed to fetch') {
    // change the message, or handle as needed:
    error.message = 'Oops, looks like the service is down :-(';
  }