Axios обработка ошибок сервера

Используя параметр конфигурации validateStatus, вы можете определить HTTP-коды, которые должны вызывать ошибку.

Обработка ошибок

axios.get('/user/12345')
  .catch(function (error) {
    if (error.response) {
      // Запрос был сделан, и сервер ответил кодом состояния, который
      // выходит за пределы 2xx
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // Запрос был сделан, но ответ не получен
      // `error.request`- это экземпляр XMLHttpRequest в браузере и экземпляр
      // http.ClientRequest в node.js
      console.log(error.request);
    } else {
      // Произошло что-то при настройке запроса, вызвавшее ошибку
      console.log('Error', error.message);
    }
    console.log(error.config);
  });

Используя параметр конфигурации validateStatus, вы можете определить HTTP-коды, которые должны вызывать ошибку.

axios.get('/user/12345', {
  validateStatus: function (status) {
    return status < 500; // Разрешить, если код состояния меньше 500
  }
})

Используя toJSON, вы получаете объект с дополнительной информацией об ошибке HTTP.

axios.get('/user/12345')
  .catch(function (error) {
    console.log(error.toJSON());
  });

axios.get('/user/12345')
  .catch(function (error) {
    if (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(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
    console.log(error.config);
  });

Using the validateStatus config option, you can define HTTP code(s) that should throw an error.

axios.get('/user/12345', {
  validateStatus: function (status) {
    return status < 500; // Resolve only if the status code is less than 500
  }
})

Using toJSON you get an object with more information about the HTTP error.

axios.get('/user/12345')
  .catch(function (error) {
    console.log(error.toJSON());
  });

I’m trying to understand javascript promises better with Axios. What I pretend is to handle all errors in Request.js and only call the request function from anywhere without having to use catch().

In this example, the response to the request will be 400 with an error message in JSON.

This is the error I’m getting:

Uncaught (in promise) Error: Request failed with status code 400

The only solution I find is to add .catch(() => {}) in Somewhere.js but I’m trying to avoid having to do that. Is it possible?

Here’s the code:

Request.js

export function request(method, uri, body, headers) {
  let config = {
    method: method.toLowerCase(),
    url: uri,
    baseURL: API_URL,
    headers: { 'Authorization': 'Bearer ' + getToken() },
    validateStatus: function (status) {
      return status >= 200 && status < 400
    }
  }

  ...

  return axios(config).then(
    function (response) {
      return response.data
    }
  ).catch(
    function (error) {
      console.log('Show error notification!')
      return Promise.reject(error)
    }
  )
}

Somewhere.js

export default class Somewhere extends React.Component {

  ...

  callSomeRequest() {
    request('DELETE', '/some/request').then(
      () => {
        console.log('Request successful!')
      }
    )
  }

  ...

}

asked Apr 22, 2018 at 15:45

mignz's user avatar

4

Actually, it’s not possible with axios as of now. The status codes which falls in the range of 2xx only, can be caught in .then().

A conventional approach is to catch errors in the catch() block like below:

axios.get('/api/xyz/abcd')
  .catch(function (error) {
    if (error.response) {
      // Request made and server responded
      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
      console.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }

  });

Another approach can be intercepting requests or responses before they are handled by then or catch.

axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    // Do something with response data
    return response;
  }, function (error) {
    // Do something with response error
    return Promise.reject(error);
  });

answered Aug 9, 2018 at 13:26

Plabon Dutta's user avatar

Plabon DuttaPlabon Dutta

6,5493 gold badges29 silver badges32 bronze badges

7

If you want to gain access to the whole the error body, do it as shown below:

 async function login(reqBody) {
  try {
    let res = await Axios({
      method: 'post',
      url: 'https://myApi.com/path/to/endpoint',
      data: reqBody
    });

    let data = res.data;
    return data;
  } catch (error) {
    console.log(error.response); // this is the main part. Use the response property from the error object

    return error.response;
  }

}

answered Mar 24, 2020 at 5:22

elonaire's user avatar

elonaireelonaire

1,7681 gold badge9 silver badges16 bronze badges

1

You can go like this:
error.response.data
In my case, I got error property from backend. So, I used error.response.data.error

My code:

axios
  .get(`${API_BASE_URL}/students`)
  .then(response => {
     return response.data
  })
  .then(data => {
     console.log(data)
  })
  .catch(error => {
     console.log(error.response.data.error)
  })

answered Mar 26, 2020 at 14:08

Md Abdul Halim Rafi's user avatar

0

If you wan’t to use async await try

export const post = async ( link,data ) => {
const option = {
    method: 'post',
    url: `${URL}${link}`,
    validateStatus: function (status) {
        return status >= 200 && status < 300; // default
      },
    data
};

try {
    const response = await axios(option);
} catch (error) {
    const { response } = error;
    const { request, ...errorObject } = response; // take everything but 'request'
    console.log(errorObject);
}

Ben T's user avatar

Ben T

4,4663 gold badges21 silver badges22 bronze badges

answered Oct 16, 2019 at 15:59

user4920718's user avatar

user4920718user4920718

1,0351 gold badge9 silver badges12 bronze badges

1

I tried using the try{}catch{} method but it did not work for me. However, when I switched to using .then(...).catch(...), the AxiosError is caught correctly that I can play around with. When I try the former when putting a breakpoint, it does not allow me to see the AxiosError and instead, says to me that the caught error is undefined, which is also what eventually gets displayed in the UI.

Not sure why this happens I find it very trivial. Either way due to this, I suggest using the conventional .then(...).catch(...) method mentioned above to avoid throwing undefined errors to the user.

Dharman's user avatar

Dharman

29.3k21 gold badges80 silver badges131 bronze badges

answered Feb 2, 2021 at 8:02

Farhan Kassam's user avatar

1

For reusability:

create a file errorHandler.js:

export const errorHandler = (error) => {
  const { request, response } = error;
  if (response) {
    const { message } = response.data;
    const status = response.status;
    return {
      message,
      status,
    };
  } else if (request) {
    //request sent but no response received
    return {
      message: "server time out",
      status: 503,
    };
  } else {
    // Something happened in setting up the request that triggered an Error
    return { message: "opps! something went wrong while setting up request" };
  }
};

Then, whenever you catch error for axios:

Just import error handler from errorHandler.js and use like this.
  try {
    //your API calls 
  } catch (error) {
    const { message: errorMessage } = errorHandlerForAction(error);
     //grab message
  }

answered Jan 12, 2022 at 15:51

Sundar Gautam's user avatar

If I understand correctly you want then of the request function to be called only if request is successful, and you want to ignore errors. To do that you can create a new promise resolve it when axios request is successful and never reject it in case of failure.

Updated code would look something like this:

export function request(method, uri, body, headers) {
  let config = {
    method: method.toLowerCase(),
    url: uri,
    baseURL: API_URL,
    headers: { 'Authorization': 'Bearer ' + getToken() },
    validateStatus: function (status) {
      return status >= 200 && status < 400
    }
  }


  return new Promise(function(resolve, reject) {
    axios(config).then(
      function (response) {
        resolve(response.data)
      }
    ).catch(
      function (error) {
        console.log('Show error notification!')
      }
    )
  });

}

answered Feb 10, 2021 at 22:19

Damir Miladinov's user avatar

Damir MiladinovDamir Miladinov

1,0741 gold badge10 silver badges15 bronze badges

1

https://stackabuse.com/handling-errors-with-axios/

    let res = await axios.get('/my-api-route');

    // Work with the response...
} catch (err) {
    if (err.response) {
        // The client was given an error response (5xx, 4xx)
    } else if (err.request) {
        // The client never received a response, and the request was never left
    } else {
        // Anything else
    }
}
try {
    let res = await axios.get('/my-api-route');

    // Work with the response...
} catch (err) {
    if (err.response) {
        // The client was given an error response (5xx, 4xx)
    } else if (err.request) {
        // The client never received a response, and the request was never left
        console.log(err.request);
    } else {
        // Anything else
    }
}

answered Jun 6, 2022 at 7:50

Berkay Nayman's user avatar

call the request function from anywhere without having to use catch().

First, while handling most errors in one place is a good Idea, it’s not that easy with requests. Some errors (e.g. 400 validation errors like: «username taken» or «invalid email») should be passed on.

So we now use a Promise based function:

const baseRequest = async (method: string, url: string, data: ?{}) =>
  new Promise<{ data: any }>((resolve, reject) => {
    const requestConfig: any = {
      method,
      data,
      timeout: 10000,
      url,
      headers: {},
    };

    try {
      const response = await axios(requestConfig);
      // Request Succeeded!
      resolve(response);
    } catch (error) {
      // Request Failed!

      if (error.response) {
        // Request made and server responded
        reject(response);
      } else if (error.request) {
        // The request was made but no response was received
        reject(response);
      } else {
        // Something happened in setting up the request that triggered an Error
        reject(response);
      }
    }
  };

you can then use the request like

try {
  response = await baseRequest('GET', 'https://myApi.com/path/to/endpoint')
} catch (error) {
  // either handle errors or don't
}

answered Feb 24, 2020 at 12:35

David Schumann's user avatar

David SchumannDavid Schumann

12.7k8 gold badges70 silver badges89 bronze badges

2

One way of handling axios error for response type set to stream that worked for me.

.....
.....
try{
   .....
   .....
   // make request with responseType: 'stream'
   const url = "your url";
   const response = axios.get(url, { responseType: "stream" });
   // If everything OK, pipe to a file or whatever you intended to do
   // with the response stream
   .....
   .....
} catch(err){
  // Verify it's axios error
  if(axios.isAxios(err)){
    let errorString = "";
    const streamError = await new Promise((resolve, reject) => {
      err.response.data
        .on("data", (chunk) => {
           errorString += chunk;
          }
        .on("end", () => {
           resolve(errorString);
         }
      });
    // your stream error is stored at variable streamError.
    // If your string is JSON string, then parse it like this
    const jsonStreamError = JSON.parse(streamError as string);
    console.log({ jsonStreamError })
    // or do what you usually do with your error message
    .....
    .....
  }
  .....
  .....
}
   
  

answered Oct 10, 2021 at 8:58

Bikash's user avatar

BikashBikash

1601 silver badge6 bronze badges

If I understand you correctly, you want some kind of global handler, so you don’t have to attach a catch handler to every request you make. There is a window event for that called unhandledrejection.

You can read more about this Event in the official documentation: https://developer.mozilla.org/en-US/docs/Web/API/Window/unhandledrejection_event

Here is how you can attach a listener for this Event:

window.addEventListener('unhandledrejection', (event) => {
  // Handle errors here...
});

answered Dec 1, 2022 at 9:15

David's user avatar

DavidDavid

516 bronze badges

React

Когда вы делаете вызов к бэкенд API с axios, вы должны рассмотреть, что делать с блоком .catch() вашего промиса. Теперь вам может показаться, что ваш API высокодоступен и он будет работать 24/7, что рабочий процесс пользователя довольно ясен, ваш JavaScript вменяем и у вас есть модульные тесты. Поэтому, когда вы смотрите на блок catch при выполнении запросов с помощью axios, вы можете подумать: “Ну… Я просто использую console.log. Все будет в порядке.”

Skillfactory.ru

axios.get('/my-highly-available-api')
  .then(response => { 
    // do stuff 
  }) 
  .catch(err => { 
    // what now? 
    console.log(err); 
  })

Но есть еще так много вещей, которые находятся вне вашего контроля, которые могут вызвать ошибки при выполнении запросов API — и вы, вероятно, даже не знаете, что они происходят!

Эта статья посвящена в основном ошибкам, которые вы видите в браузере. На бэкенде тоже все может выглядеть довольно забавно. Просто взгляните на три вещи, которые вы можете увидеть в своих бэкенд журналах.

Ниже приведены три типа ошибок, которые могут появиться, и как их обрабатывать при использовании axios.

Отлов ошибок Axios

Ниже приведен фрагмент кода, который я начал включать в несколько проектов JS:

axios.post(url, data)
  .then(res => { 
    // do good things 
  }) 
  .catch(err => { 
    if (err.response) { 
      // client received an error response (5xx, 4xx)
    } else if (err.request) { 
      // client never received a response, or request never left 
    } else { 
      // anything else 
    } 
  })

Каждое условие предназначено для фиксации различного типа ошибки.

Проверка error.response

Если ваш объект error содержит поле response, это означает, что сервер ответил с ошибкой 4xx/5xx. Обычно это та ошибка, с которой мы лучше всего знакомы и с которой легче всего справиться.

Применяйте следующее: “Показать страницу 404 Not Found / сообщение об ошибке, если ваш API возвращает 404.” Покажите другое сообщение об ошибке, если ваш бэкенд возвращает 5xx или вообще ничего не возвращает. Вы может показаться, что ваш хорошо сконструированный бэкенд не будет генерировать ошибки, но это всего лишь вопрос времени, а не “если”.

Проверка error.request

Второй класс ошибок — это когда у вас нет ответа, но есть поле request, прикрепленное к ошибке. Когда же это происходит? Это происходит, когда браузер смог сделать запрос, но по какой-то причине не получил ответа. Это может произойти, если:

• Вы находитесь в обрывочной сети (например, в метро или используете беспроводную сеть здания).

• Ваш бэкенд зависает на каждом запросе и не возвращает ответ вовремя.

• Вы делаете междоменные запросы, но вы не авторизованы, чтобы их делать.

• Вы делаете междоменные запросы, и вы авторизованы, но бэкенд API возвращает ошибку.

Одна из наиболее распространенных версий этой ошибки имела бесполезное сообщение “Ошибка сети”. У нас есть API для фронтенда и бэкенда, размещенные в разных доменах, поэтому каждый вызов к бэкенд API — это междоменный запрос.

Из-за ограничений безопасности на JS в браузере, если вы делаете запрос API, и он не работает из-за плохих сетей, единственная ошибка, которую вы увидите — это “Ошибка сети”, которая невероятно бесполезна. Она может означать что угодно: от “Ваше устройство не имеет подключения к Интернету” до “Ваши OPTIONS вернули 5xx” (если вы делаете запросы CORS). Причина ошибки сети хорошо описана в этом ответе на StackOverflow.

Все остальные типы ошибок

Если ваш объект error не содержит поля response или request, это означает, что это не ошибка axios и, скорее всего, в вашем приложении что-то еще не так. Сообщение об ошибке + трассировка стека должны помочь вам понять, откуда оно исходит.

Как вам их исправить?

Ухудшение пользовательского опыта

Все это зависит от вашего приложения. Для проектов, над которыми я работаю, для каждой функции, использующей эти конечные точки, мы ухудшаем пользовательский опыт.

Например, если запрос не выполняется и страница бесполезна без этих данных, то у нас будет большая страница ошибок, которая появится и предложит пользователям выход — иногда это всего лишь кнопка “Обновить страницу”.

Другой пример: если запрос на изображение профиля в потоке социальных сетей не выполняется, мы можем показать изображение-плейсхолдер и отключить изменения изображения профиля вместе с всплывающим уведомлением, объясняющим, почему кнопка “Обновить изображение профиля” отключена. Однако показывать предупреждение с надписью “422 необработанных объекта” бесполезно для пользователя.

Skillfactory.ru

Обрывистые сети

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

Для решения такого рода периодических проблем с сетью, мы добавили axios-retry, что решило большое количество ошибок, которые мы наблюдали в продакшне. Это было добавлено в нашу настройку axios:

const _axios = require('axios') 
const axiosRetry = require('axios-retry') 
const axios = _axios.create() 
// https://github.com/softonic/axios-retry/issues/87 const retryDelay = (retryNumber = 0) => { 
  const seconds = Math.pow(2, retryNumber) * 1000; 
  const randomMs = 1000 * Math.random(); 
  return seconds + randomMs; 
}; 
axiosRetry(axios, { 
  retries: 2, 
  retryDelay, 
  // retry on Network Error & 5xx responses 
  retryCondition: axiosRetry.isRetryableError, 
}); 
module.exports = axios;

Мы увидели, что 10% наших пользователей (которые находятся в плохих школьных сетях) периодически наблюдали ошибки сети, но число снизилось до <2% после добавления автоматических повторных попыток при сбое.

Скриншот количества ошибок сети, как они появляются в браузере New Relic. <1% запросов неверны. Это подводит меня к последнему пункту.

Добавляйте отчеты об ошибках в свой интерфейс

Полезно иметь отчеты об ошибках и событиях фронтенда, чтобы вы знали, что происходит в разработке, прежде чем ваши пользователи сообщат вам о них. На моей основной работе мы используем браузер New Relic для отправки событий ошибок с фронтенда. Поэтому всякий раз, когда мы ловим исключение, мы регистрируем сообщение об ошибке вместе с трассировкой стека (хотя это иногда бесполезно с минимизированными пакетами) и некоторыми метаданными о текущем сеансе, чтобы попытаться воссоздать его.

Другие инструменты, используемые нами— Sentry + SDK браузер, Rollbar и целая куча других полезных инструментов, перечисленных на GitHub.

Заключение

Если вы больше ничего не можете выжать из этого, сделайте одно: перейдите в свою кодовую базу и просмотрите, как вы обрабатываете ошибки с помощью axios.

  • Проверьте, выполняете ли вы автоматические повторы, и, если нет, добавьте axios-retry.
  • Проверьте, что вы отлавливаете ошибки и сообщаете пользователю, что что-то произошло. Использовать только axios.get(...).catch(console.log) недостаточно.

Читайте также:

  • React TypeScript: Основы и лучшие практики
  • Первые шаги в анимации React Native
  • Как предотвратить состояние гонки с помощью React Context API

Перевод статьи Danny Perez: How to Handle API Errors in Your Web App Using Axios

Note: If you want to see how to handle these in React, take a look at my new post on that here — handling async errors with axios in react.

Whenever you’re making a backend API call with axios, you have to consider what to do with the .catch() block of your promise. Now, you might think that your API is highly available and it’ll be running 24/7. You might think that the user workflow is pretty clear, your javascript is sane, and you have unit tests. So when you stare at the catch block when making requests using axios you might think — «Well… I’ll just console.log it. That’ll be fine.»

axios.get('/my-highly-available-api').then(response => {
    // do stuff
})
.catch(err => {
    // what now?
    console.log(err);
})

But there are so many many many more things that are outside of your control that could throw errors when making API requests. And you probably don’t even know that they’re happening!

This post deals mainly with errors you see in the browser. Things can get pretty funny looking on the back end too — just take a look at 3 things you might see in your backend logs

Below are 3 types of errors that could appear, and how to handle it, when using axios.

Catching axios errors

Below is a snippet I’ve started including in a few JS projects.

axios.post(url, data).then(res => {
        // do good things
})
.catch(err => {
    if (err.response) {
      // client received an error response (5xx, 4xx)
    } else if (err.request) {
      // client never received a response, or request never left
    } else {
      // anything else
    }
})

Each condition is meant to capture a different type of error.

Checking error.response

If your error object contains a response field, that means your server responded with a 4xx/5xx error. Usually this is the error we’re most familiar with, and is most straightforward to handle.

Do things like a show a 404 Not Found page/error message if your API returns a 404. Show a different error message if your backend is returning a 5xx or not returning anything at all. You might think your well-architected backend won’t throw errors — but its a matter of when, not if.

Checking error.request

The second class of errors is where you don’t have a response but there’s a request field attached to the error. When does this happen? This happens when the browser was able to make a request, but for some reason, it didn’t see a response.

This can happen if:

  • you’re in a spotty network (think underground subway, or a building wireless network)
  • if your backend is hanging on each request and not returning a response on time
  • if you are making cross-domain requests and you’re not authorized to make the request
  • if you’re making cross-domain requests and you are authorized, but the backend API returns an error

One of the more common versions of this error had a message «Network Error» which is a useless error message. We have a front-end and a backend api hosted on different domains, so every backend API call is a cross-domain request.

Due to security constraints on JS in the browser, if you make an API request, and it fails due to crappy networks, the only error you’ll see is «Network Error» which is incredibly unhelpful. It can mean anything from «your device doesn’t have internet connectivity» to «your OPTIONS returned a 5xx» (if you make CORS requests). The reason for «Network Error» is described well here on this StackOverflow answer

All the other types of errors

If your error object doesn’t have the response or request field on it, that means its not an axios error and theres likely something else wrong in your app. The error message + stack trace should help you figure out where its coming from.

How do you fix it?

Degrading the user experience

This all depends on your app. For the projects I work on, for each of the features that use those endpoints, we degrade the user experience.

For example, if the request fails, and the page is useless without that data, then we have a bigger error page that will appear and offer users a way out — which sometimes is only a «Refresh the page» button.

Another example, if a request fails for a profile picture in a social media stream, we can show a placeholder image and disable profile picture changes, along with a toaster message explaining why the «update profile picture» button is disabled. However, showing an alert saying «422 Unprocessable Entity» is useless to see as a user.

Spotty networks

The web client I work on is used in school networks which can be absolutely terrible. The availability of your backend barely has anything to do with it, the request sometimes fail to leave the school network.

To solve these types of intermittent network problems, we added in axios-retry. This solved a good amount of the errors we were seeing in production. We added this to our axios setup:

const _axios = require('axios')
const axiosRetry = require('axios-retry')

const axios = _axios.create()

// https://github.com/softonic/axios-retry/issues/87
const retryDelay = (retryNumber = 0) => {
    const seconds = Math.pow(2, retryNumber) * 1000;
    const randomMs = 1000 * Math.random();
    return seconds + randomMs;
};

axiosRetry(axios, {
    retries: 2,
    retryDelay,
    // retry on Network Error & 5xx responses
    retryCondition: axiosRetry.isRetryableError,
});

module.exports = axios;

We were able to see that 10% of our users (which are in crappy school networks) were seeing sporadic «Network Errors» and that dropped down to <2% after adding in automatic retries on failure.

chart showing count of Network Errors

^ This is a screenshot of our errors is the count of «Network Errors» as they appear in NewRelic and are showing <1% of requests are erroring out.

Which leads to my last point:

Add error reporting to your front-end

Its helpful to have front-end error/event reporting so that you know whats happening in prod before your users tell you. At my day job, we use NewRelic Browser (paid service — no affiliation, just a fan) to send error events from the front-end. So whenever we catch an exception, we log the error message, along with the stack trace (although thats sometimes useless with minified bundles), and some metadata about the current session so we can try to recreate it.

Other tools that fill this space are Sentry + browser SDK, Rollbar, and a whole bunch of other useful ones listed here

Wrapping up

If you get nothing else out of this, do one thing.

Go to your code base now, and review how you’re handling errors with axios.

  • Check if you’re doing automatic retries, and consider adding axios-retry if you aren’t
  • Check that you’re catching errors, and letting the user know that something has happened. axios.get(...).catch(console.log) isn’t good enough.

So. How do you handle your errors? Let me know in the comments.

Содержание

  1. Обработка ошибок API в веб-приложении, используя Axios
  2. Отлов ошибок Axios
  3. Проверка error.response
  4. Проверка error.request
  5. Все остальные типы ошибок
  6. Как вам их исправить?
  7. Ухудшение пользовательского опыта
  8. Обрывистые сети
  9. Используем axios для доступа к API
  10. Простой пример
  11. Пример из жизни: работа с данными
  12. Отображение данных из API
  13. Обработка ошибок
  14. Альтернативы
  15. Fetch API
  16. Итоги
  17. axios
  18. axios
  19. Features
  20. Browser Support
  21. Installing
  22. Example
  23. axios API
  24. Request method aliases
  25. Concurrency
  26. Creating an instance
  27. Instance methods
  28. Request Config
  29. Response Schema
  30. Config Defaults
  31. Global axios defaults
  32. Custom instance defaults
  33. Config order of precedence
  34. Interceptors
  35. Handling Errors
  36. Cancellation
  37. Using application/x-www-form-urlencoded format
  38. Browser
  39. Node.js
  40. Semver
  41. Promises
  42. TypeScript
  43. Resources
  44. Credits

Обработка ошибок API в веб-приложении, используя Axios

Когда вы делаете вызов к бэкенд API с axios, вы должны рассмотреть, что делать с блоком .catch() вашего промиса. Теперь вам может показаться, что ваш API высокодоступен и он будет работать 24/7, что рабочий процесс пользователя довольно ясен, ваш JavaScript вменяем и у вас есть модульные тесты. Поэтому, когда вы смотрите на блок catch при выполнении запросов с помощью axios , вы можете подумать: “Ну… Я просто использую console.log . Все будет в порядке.”

Но есть еще так много вещей, которые находятся вне вашего контроля, которые могут вызвать ошибки при выполнении запросов API — и вы, вероятно, даже не знаете, что они происходят!

Эта статья посвящена в основном ошибкам, которые вы видите в браузере. На бэкенде тоже все может выглядеть довольно забавно. Просто взгляните на три вещи, которые вы можете увидеть в своих бэкенд журналах.

Ниже приведены три типа ошибок, которые могут появиться, и как их обрабатывать при использовании axios.

Отлов ошибок Axios

Ниже приведен фрагмент кода, который я начал включать в несколько проектов JS:

Каждое условие предназначено для фиксации различного типа ошибки.

Проверка error.response

Если ваш объект error содержит поле response , это означает, что сервер ответил с ошибкой 4xx/5xx. Обычно это та ошибка, с которой мы лучше всего знакомы и с которой легче всего справиться.

Применяйте следующее: “Показать страницу 404 Not Found / сообщение об ошибке, если ваш API возвращает 404.” Покажите другое сообщение об ошибке, если ваш бэкенд возвращает 5xx или вообще ничего не возвращает. Вы может показаться, что ваш хорошо сконструированный бэкенд не будет генерировать ошибки, но это всего лишь вопрос времени, а не “если”.

Проверка error.request

Второй класс ошибок — это когда у вас нет ответа, но есть поле request , прикрепленное к ошибке. Когда же это происходит? Это происходит, когда браузер смог сделать запрос, но по какой-то причине не получил ответа. Это может произойти, если:

• Вы находитесь в обрывочной сети (например, в метро или используете беспроводную сеть здания).

• Ваш бэкенд зависает на каждом запросе и не возвращает ответ вовремя.

• Вы делаете междоменные запросы, но вы не авторизованы, чтобы их делать.

• Вы делаете междоменные запросы, и вы авторизованы, но бэкенд API возвращает ошибку.

Одна из наиболее распространенных версий этой ошибки имела бесполезное сообщение “Ошибка сети”. У нас есть API для фронтенда и бэкенда, размещенные в разных доменах, поэтому каждый вызов к бэкенд API — это междоменный запрос.

Из-за ограничений безопасности на JS в браузере, если вы делаете запрос API, и он не работает из-за плохих сетей, единственная ошибка, которую вы увидите — это “Ошибка сети”, которая невероятно бесполезна. Она может означать что угодно: от “Ваше устройство не имеет подключения к Интернету” до “Ваши OPTIONS вернули 5xx” (если вы делаете запросы CORS). Причина ошибки сети хорошо описана в этом ответе на StackOverflow.

Все остальные типы ошибок

Если ваш объект error не содержит поля response или request , это означает, что это не ошибка axios и, скорее всего, в вашем приложении что-то еще не так. Сообщение об ошибке + трассировка стека должны помочь вам понять, откуда оно исходит.

Как вам их исправить?

Ухудшение пользовательского опыта

Все это зависит от вашего приложения. Для проектов, над которыми я работаю, для каждой функции, использующей эти конечные точки, мы ухудшаем пользовательский опыт.

Например, если запрос не выполняется и страница бесполезна без этих данных, то у нас будет большая страница ошибок, которая появится и предложит пользователям выход — иногда это всего лишь кнопка “Обновить страницу”.

Другой пример: если запрос на изображение профиля в потоке социальных сетей не выполняется, мы можем показать изображение-плейсхолдер и отключить изменения изображения профиля вместе с всплывающим уведомлением, объясняющим, почему кнопка “Обновить изображение профиля” отключена. Однако показывать предупреждение с надписью “422 необработанных объекта” бесполезно для пользователя.

Обрывистые сети

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

Для решения такого рода периодических проблем с сетью, мы добавили axios-retry, что решило большое количество ошибок, которые мы наблюдали в продакшне. Это было добавлено в нашу настройку axios:

Мы увидели, что 10% наших пользователей (которые находятся в плохих школьных сетях) периодически наблюдали ошибки сети, но число снизилось до

Источник

Используем axios для доступа к API

Простой пример

Неоднократно при создании веб-приложения вам может понадобиться получать и отображать данные из API. Существует несколько способов сделать это, но наиболее популярным решением является использование axios, основанного на Promise HTTP-клиента.

В этом упражнении мы будем использовать CoinDesk API для отображения цен на Биткойн, обновляемых каждую минуту. Прежде всего, подключим axios с помощью npm, yarn или ссылки на CDN.

Существует множество вариантов, как мы можем запрашивать информацию из API, но прежде необходимо узнать, в каком виде предоставляются данные, чтобы понимать, как их отображать. Для этого сделаем запрос к конечной точке (endpoint) API и выведем результат. Как можно убедиться из документации API CoinDesk, для получения данных мы будем делать запрос на https://api.coindesk.com/v1/bpi/currentprice.json . Изначально необходимо создать свойство в data для хранения нашей информации, далее извлечём и сохраним данные, используя хук жизненного цикла mounted .

И вот что мы получаем:

Отлично! Мы получили какие-то данные. Но сейчас они выглядят достаточно грязно, так что давайте отобразим их должным образом и добавим обработку ошибок на случай, если что-то пойдёт не так, либо когда для получения информации потребовалось больше времени.

Пример из жизни: работа с данными

Отображение данных из API

Типичная ситуация, когда необходимая информация находится внутри ответа сервера и нам необходимо знать структуру данных для получения доступа. В нашем случае, нужная информация о цене находится в response.data.bpi . Если мы используем это, то запрос будет выглядеть следующим образом.

Такие данные намного проще отображать, так что мы можем сейчас обновить HTML-разметку для отображения только нужной информации из полученных данных. Создадим фильтр, чтобы десятичные значения всегда отображались как нужно.

Обработка ошибок

Бывают моменты, когда мы не получили необходимые данные из API. Может быть множество причин, из-за которых вызов axios мог закончиться неудачей, например:

  • API не был доступен.
  • Запрос был сделан неправильно.
  • API не предоставил данные в ожидаемом нами формате.

При выполнении этого запроса мы должны проверять такие обстоятельства и предоставлять информацию в каждом случае, чтобы мы знали, как справиться с этой проблемой. В вызове axios мы сделаем это, используя catch .

Так мы узнаем, если что-то пойдёт не так во время запроса к API. Но что если данные повреждены или API не был доступен? Сейчас пользователь просто ничего не увидит. Мы могли бы использовать индикатор загрузки для этого случая и сообщать пользователю, что не можем получить данные.

Вы можете нажимать на кнопку перезапуска (находится в правом нижнем углу во вкладке Result), чтобы увидеть индикатор загрузки во время получения данных из API.

В дальнейшем код можно улучшить с помощью компонентов для различных секций и более детальными отчётами об ошибках. Это зависит от используемого API и сложности вашего приложения.

Альтернативы

Fetch API

Fetch API — мощный нативный API для создания запросов. Может вы слышали, что одно из преимуществ Fetch API в том, что не нужно загружать внешние зависимости для его использования, что является правдой! Однако… он ещё не полностью поддерживается браузерами, поэтому всё равно необходимо использовать полифил. Есть подводные камни при работе с его API, поэтому многие сейчас предпочитают axios. В будущем это может измениться.

Если вы заинтересовались Fetch API — существуют очень хорошие статьи, где объясняются тонкости его использования.

Итоги

Существует множество способов работы с Vue и axios, выходящие за рамки получения и отображения данных из API. Вы можете также взаимодействовать с бессерверными функциями (Serverless Functions), публикацией/редактированием/удалением через API, к которому вы имеете доступ, и т.д. Простая интеграция этих двух библиотек сделала axios очень распространённым выбором среди разработчиков, которым необходимо интегрировать HTTP-клиенты в их приложения.

Источник

axios

жњ¬з«™з”±axios爱好者共建,部署在vultr vpsдёЉпјЊжЋЁиЌђдЅїз”Ёvultr!д»·ж је®ћжѓ пјЊе®ћеЉ›й›„еЋљгЂ‚ жњЂиї‘ж–°жіЁе†Њз”Ёж€·е……еЂј$25,еЏЇйўќе¤–иЋ·иµ $50,搭建博客必备。 е‰ЌеѕЂжіЁе†Њ

axios





Promise based HTTP client for the browser and node.js

Features

  • Make XMLHttpRequests from the browser
  • Make http requests from node.js
  • Supports the Promise API
  • Intercept request and response
  • Transform request and response data
  • Cancel requests
  • Automatic transforms for JSON data
  • Client side support for protecting against XSRF

Browser Support

Latest вњ” Latest вњ” Latest вњ” Latest вњ” Latest вњ” 11 вњ”

Installing

Example

Performing a GET request

NOTE: async/await is part of ECMAScript 2017 and is not supported in Internet
Explorer and older browsers, so use with caution.

Performing a POST request

Performing multiple concurrent requests

axios API

Requests can be made by passing the relevant config to axios .

axios(config)
axios(url[, config])

Request method aliases

For convenience aliases have been provided for all supported request methods.

axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])

When using the alias methods url , method , and data properties don’t need to be specified in config.

Concurrency

Helper functions for dealing with concurrent requests.

axios.all(iterable)
axios.spread(callback)

Creating an instance

You can create a new instance of axios with a custom config.

axios.create([config])

Instance methods

The available instance methods are listed below. The specified config will be merged with the instance config.

axios#request(config)
axios#get(url[, config])
axios#delete(url[, config])
axios#head(url[, config])
axios#options(url[, config])
axios#post(url[, data[, config]])
axios#put(url[, data[, config]])
axios#patch(url[, data[, config]])
axios#getUri([config])

Request Config

These are the available config options for making requests. Only the url is required. Requests will default to GET if method is not specified.

Response Schema

The response for a request contains the following information.

When using then , you will receive the response as follows:

When using catch , or passing a rejection callback as second parameter of then , the response will be available through the error object as explained in the Handling Errors section.

Config Defaults

You can specify config defaults that will be applied to every request.

Global axios defaults

Custom instance defaults

Config order of precedence

Config will be merged with an order of precedence. The order is library defaults found in lib/defaults.js, then defaults property of the instance, and finally config argument for the request. The latter will take precedence over the former. Here’s an example.

Interceptors

You can intercept requests or responses before they are handled by then or catch .

If you may need to remove an interceptor later you can.

You can add interceptors to a custom instance of axios.

Handling Errors

You can define a custom HTTP status code error range using the validateStatus config option.

Cancellation

You can cancel a request using a cancel token.

The axios cancel token API is based on the withdrawn cancelable promises proposal.

You can create a cancel token using the CancelToken.source factory as shown below:

You can also create a cancel token by passing an executor function to the CancelToken constructor:

Note: you can cancel several requests with the same cancel token.

Using application/x-www-form-urlencoded format

By default, axios serializes JavaScript objects to JSON . To send data in the application/x-www-form-urlencoded format instead, you can use one of the following options.

Browser

In a browser, you can use the URLSearchParams API as follows:

Note that URLSearchParams is not supported by all browsers (see caniuse.com), but there is a polyfill available (make sure to polyfill the global environment).

Alternatively, you can encode data using the qs library:

Or in another way (ES6),

Node.js

In node.js, you can use the querystring module as follows:

You can also use the qs library.

Semver

Until axios reaches a 1.0 release, breaking changes will be released with a new minor version. For example 0.5.1 , and 0.5.4 will have the same API, but 0.6.0 will have breaking changes.

Promises

axios depends on a native ES6 Promise implementation to be supported.
If your environment doesn’t support ES6 Promises, you can polyfill.

TypeScript

axios includes TypeScript definitions.

Resources

Credits

axios is heavily inspired by the $http service provided in Angular. Ultimately axios is an effort to provide a standalone $http -like service for use outside of Angular.

Источник

Introduction

Axios is a JavaScript library that uses the Promise API to create HTTP requests with http in Node.js runtime or XMLHttpRequests in the browser. Because these requests are promises, they work with the newer async/await syntax, as well as .then() functions for promise chaining and the .catch() mechanism for error handling.

try {
    let res = await axios.get('/my-api-route');

    // Work with the response...
} catch (err) {
    // Handle error
    console.log(err);
}

In this article, we will see how to handle errors with Axios, as this is very important when making any HTTP calls knowing fully well that there are times when the service you’re calling might not be available or return other unexpected errors. We’ll show the .then()/.catch() method, but primarily use the async/await syntax.

Then and Catch

Promises can be handled in two ways using modern JS — the async/await syntax, which was shown above, as well as .then() and .catch() methods. Note that both of these methods can produce the same functionality, but async/await is typically regarded as being easier to work with and requires less boilerplate code in longer promise chains.

Here is how you’d achieve the same thing, but using the then/catch method:

axios.get('/my-api-route')
    .then(res => {
        // Work with the response...
    }).catch(err => {
        // Handle error
        console.log(err);
    });

Both the res and err objects are the same as with the async/await syntax.

Handling Errors

In this section, we will look at two primary categories of problems, as well as other issues that we may encounter and how to manage them using Axios. It is critical that you understand that this applies to all types of HTTP queries handled by Axios, including GET, POST, PATCH, and so on.

Here you can see the syntax for the three aspects — this will capture the error; it is crucial to note that this error carries a large error object with a lot of information:

try {
    let res = await axios.get('/my-api-route');

    // Work with the response...
} catch (err) {
    if (err.response) {
        // The client was given an error response (5xx, 4xx)
    } else if (err.request) {
        // The client never received a response, and the request was never left
    } else {
        // Anything else
    }
}

The differences in the error object, highlighted above in the catch code, indicate where the request encountered the issue. We’ll look deeper into this in the following sections.

error.response

This is the type of mistake we are most familiar with, and it is much easier to deal with. Many sites display a 404 Not Found page/error message or various response codes based on what the API provides; this is often handled via the response.

If your error object has a response property, it signifies your server returned a 4xx/5xx error. This will assist you choose what sort of message to return to users; the message you’ll want to provide for 4xx may differ from that for 5xx, and if your backend isn’t returning anything at all.

try {
    let res = await axios.get('/my-api-route');

    // Work with the response...
} catch (err) {
    if (err.response) {
        // The client was given an error response (5xx, 4xx)
        console.log(err.response.data);
        console.log(err.response.status);
        console.log(err.response.headers);
    } else if (err.request) {
        // The client never received a response, and the request was never left
    } else {
        // Anything else
    }
}

error.request

This error is most commonly caused by a bad/spotty network, a hanging backend that does not respond instantly to each request, unauthorized or cross-domain requests, and lastly if the backend API returns an error.

Note: This occurs when the browser was able to initiate a request but did not receive a valid answer for any reason.

try {
    let res = await axios.get('/my-api-route');

    // Work with the response...
} catch (err) {
    if (err.response) {
        // The client was given an error response (5xx, 4xx)
    } else if (err.request) {
        // The client never received a response, and the request was never left
        console.log(err.request);
    } else {
        // Anything else
    }
}

Earlier we mentioned that the underlying request Axios uses depends on the environment in which it’s being run. This is also the case for the err.request object. Here the err.request object is an instance of XMLHttpRequest when being executed in the browser, whereas it’s an instance of http.ClientRequest when being used in Node.js.

Other Errors

It’s possible that the error object does not have either a response or request object attached to it. In this case it is implied that there was an issue in setting up the request, which eventually triggered an error.

try {
    let res = await axios.get('/my-api-route');

    // Work with the response...
} catch (err) {
    if (err.response) {
        // The client was given an error response (5xx, 4xx)
    } else if (err.request) {
        // The client never received a response, and the request was never left
    } else {
        // Anything else
        console.log('Error', err.message);
    }
}

For example, this could be the case if you omit the URL parameter from the .get() call, and thus no request was ever made.

Conclusion

In this short article, we looked at how we may handle various sorts of failures and errors in Axios. This is also important for giving the correct message to your application/website visitors, rather than always returning a generic error message, sending a 404, or indicating network problems.

In the course of fetching APIs, if the API request doesn’t go as planned, we may encounter errors. Let’s see how to manage these errors using Axios.

If you don’t want to use the built-in Fetch API, you can opt for the many 3rd party libraries available on npm, and Axios is the most popular among them. It is essentially a wrapper around the Fetch API and allows you to make HTTP requests using a promise-based HTTP client.

API Errors

When a request to an API doesn’t go as planned, an API error occurs. So, the API must respond to the client specifying whether the request was successful or not. In this case, we should send an error response, and it is the only way for the developers to diagnose what went wrong. HTTP Status Codes are used for this purpose. The following status codes notify about the errors.

  • 4xx — Client error. Such as 404: Requested URL not found.
  • 5xx — Server error.

Informing the client about the error helps them understand the error and its cause.

Using Axios

To handle errors in a standard API call using Axios, we use a try...catch block. For example, take a look at the following code, which fetches random quotes from the Famous Quotes API from RapidAPI Hub.

js

import axios from 'axios';

const fetchQuotes = async () => {

try {

const res = await axios.get(

`https://famous-quotes4.p.rapidapi.com/random`

);

} catch (error) {

// Do something with the error here

}

};

If an error occurs, the catch block captures it. We need to add some logic in this block to handle the errors. We have to take care of three scenarios of errors:

  1. Request is made, but the server responds with an error.

  2. Request is made, but no response is received from the server.

  3. When an error occurs while setting up the request.

To handle these scenarios, we can use an if-else block like this:

js

try {

const res = await axios.get(`https://famous-quotes4.p.rapidapi.com/random`);

} catch (error) {

if (error.response) {

// Request made but the server responded with an error

} else if (error.request) {

// Request made but no response is received from the server.

} else {

// Error occured while setting up the request

}

}

It is critical to check for the request and response properties because there will be no response property if we do not receive a response. Similarly, there will be no request property if the request is not set up. Let’s take a look at these properties.

error.response

If the request is made and the server gives an error response, the error object will have a response property. It means that a 4XX or 5XX error has occurred. The response object has many properties which we can log, like the status property, which has the status code of the error.

error.request

error.request is the request object of the HTTP request that the client made. It contains information such as the HTTP method, URL, and the headers sent with the request. For Axios, it is an instance of XMLHttpRequest when running in the browser and an instance of http.ClientRequest when executed in Node.js. We use it when we do not receive a valid response from the API due to a poor network or unauthorized access.

Logging Errors

Finally, we can use these properties to log errors properly. It will look like this in code:

js

try {

const res = await axios.get(`https://famous-quotes4.p.rapidapi.com/random`);

} catch (error) {

if (error.response) {

// Request made but the server responded with an error

console.log(error.response.data);

console.log(error.response.status);

console.log(error.response.headers);

} else if (error.request) {

// Request made but no response is received from the server.

console.log(error.request);

} else {

// Error occured while setting up the request

console.log('Error', error.message);

}

}

The same goes for Axios POST, PUT, PATCH, and all other types of requests. Now you know how to manage API errors using Axios. Find a suitable API from RapidAPI Hub and integrate it into your projects using Axios.

Понравилась статья? Поделить с друзьями:
  • Axios react native network error
  • Axios post cors error
  • Axios post catch error
  • Axios json error
  • Axios interceptor error