Почему мой JavaScript Fetch не может получить объект ошибки - PullRequest
0 голосов
/ 10 октября 2018

У меня есть JavaScript, который отправляет вызов Fetch на серверную часть сайта.Если после звонка все в порядке, Fetch может обработать ответ.Если что-то пойдет не так во время пост-вызова, Fetch не сможет обработать ошибку.

Это мои коды:

async function startFetch(url, data_post){ 
  return fetch(url, {
    method: 'POST', // or 'PUT'
    body: JSON.stringify(data_post), // data can be `string` or {object}!
    headers:{  
      'Content-Type': 'application/json'
    }
  })
  .then(response => response.json());
}

async function makeFetch(arrRows){
  let url = 'somebackendpost';

  for(const item of ArrRows){
    let data_post = {};
    data.name = item;

    await startFetch(url, data_post)
    .then(data => {
      //when the fetch is okay, this part is executed
      console.log(data);
      //do other things like output to html
      $('#result').append('<p>' + data.result + '</p>');
    })
    .catch(error ={
      //a timeout 504 error occured, but this part seemed not to execute
      console.log('error is', error);
      //the code below is wrong (but has since been removed then)
      //Is this the reason why the catch error part did not work?
      //Since the code below has been removed, can I expect the catch error to now work?
      $('#result').append('<p>' + data.result + '</p>');
    });

  }
}

function startProcess(){
  //called by button click
  let arrRows = ["Row1", "Row2", "Row3"];
  makeFetch(arrRows);
}

В то время, когда код был выполнен, возникла проблема с сервером.В консоли браузера отображается ошибка тайм-аута шлюза 504. Вот журналы консоли:

Fetch failed loading: POST "mysite/somebackendpost"
POST mysite/somebackendpost 504 (GATEWAY TIMEOUT)
error is SyntaxError: Unexpected end of JSON input
 at fetch.then.response
Uncaught (in promise) ReferenceError: X is not defined
  at startFetch.then.catch.error

1 Ответ

0 голосов
/ 10 октября 2018

Попробуйте обновить метод startFetch, чтобы сначала убедиться, что ответ извлечения «в порядке», прежде чем пытаться проанализировать ответ как json.Это перехватит большинство сценариев ошибок (которые в настоящее время остаются незамеченными), прежде чем вы попытаетесь проанализировать json.

Итак, следующее обновление должно позволить вам правильно реагировать на ошибки:

async function startFetch(url, data_post){ 
  return fetch(url, {
    method: 'POST', // or 'PUT'
    body: JSON.stringify(data_post), // data can be `string` or {object}!
    headers:{  
      'Content-Type': 'application/json'
    }
  })
  .then(response => {

      // Check that the response is valid and reject an error
      // response to prevent subsequent attempt to parse json
      if(!response.ok) {
         return Promise.reject('Response not ok with status ' + response.status);
      }

      return response;
  })
  .then(response => response.json());
}

Надеюсь, это поможет!

...