реагировать топором ios тогда работает но ловить не работает - PullRequest
0 голосов
/ 15 февраля 2020

Я прочитал следующие вопросы, но не смог найти решение.

Я хочу получить ошибки 400, 500, ... кто-то сказал, что вы должны поймать тогда, но я попробовал, и ничего не произошло. для теста я написал функцию для получения ошибки 404, 400, ...

export const myAxios = url => {
  Axios.get(url)
    .then(response => {
      // Success
      console.log("then response ", response);
    })
    .catch(error => {
      // Error
      if (error.response) {
        console.log("error respone", error.response);
        // The request was made and the server responded with a status code
        // that falls out of the range of 2xx
        // console.log(error.response.data);
        // console.log(error.response.status);
        // console.log(error.response.headers);
      } else if (error.request) {
        // The request was made but no response was received
        // `error.request` is an instance of XMLHttpRequest in the
        // browser and an instance of
        // http.ClientRequest in node.js
        console.log("erros request: ", error.request);
      } else {
        // Something happened in setting up the request that triggered an Error
        console.log("Error message", error.message);
      }
      console.log("errors config : ", error.config);
    });
};

ax ios не ловит ошибки, и консоль браузера регистрирует это:

xhr.js:172 GET http://localhost:3000/app/..../choices 404 (Not Found)
dispatchXhrRequest @ xhr.js:172
xhrAdapter @ xhr.js:11
dispatchRequest @ dispatchRequest.js:59
Promise.then (async)
request @ Axios.js:53
Axios.<computed> @ Axios.js:68
wrap @ bind.js:9
myAxios @ textaxios.js:4
(anonymous) @ List.jsx:14
commitHookEffectList @ react-dom.development.js:22030

Any советы или помощь будут оценены.

пакетов:

   "axios": "^0.19.0"
   "react": "^16.12.0"

1 Ответ

0 голосов
/ 15 февраля 2020

Ваш код выглядит нормально, возможно, вы пытаетесь добраться до локальной конечной точки (ресурса)?

Вот пример использования примера службы заполнителя:

document.getElementById('btn-valid').addEventListener('click', () => {
  // Valid URL
  myAxios('https://jsonplaceholder.typicode.com/todos/1')
})

document.getElementById('btn-invalid').addEventListener('click', () => {
  // Invalid URL
  myAxios('https://jsonplaceholder.typicode.com/todus/1')
})

const myAxios = url => {
  axios.get(url)
    .then(response => {
      console.log('success', response);
    })
    .catch(error => {
      console.log('error', error)
    })
}
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>


<button id="btn-invalid">Invalid URL</button>
<button id="btn-valid">Valid URL</button>

Кроме того, вы можете попробовать использовать перехватчики Ax ios для «перехвата» запросов или ответов до их обработки then или catch:

axios.interceptors.response.use(response => {
        // Any status code that lie within the range of 2xx cause this function to trigger
        // Do something with response data
        console.log('inside interceptor success')
        return response;
      }, error => {
        // Any status codes that falls outside the range of 2xx cause this function to trigger
        // Do something with response error
        console.log('inside interceptor error')
        return Promise.reject(error);
      });
...