Programming/JavaScript

[JavaScript] Axios ์˜ค๋ฅ˜ ์ฒ˜๋ฆฌ / catch ๋ฌธ์—์„œ Status Code ๋ฐ›์•„์˜ค๋Š” ๋ฐฉ๋ฒ•

yuri lee 2022. 10. 4. 21:32
๋ฐ˜์‘ํ˜•

Intro

Axios์˜ catch() ๋ฌธ์—์„œ Status Code ๋ฅผ ๋ฐ›์•„์˜ค๋Š” ๋ฐฉ๋ฒ•์— ๋Œ€ํ•ด ์•Œ์•„๋ณด๋„๋ก ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด ๋‹ค์Œ์˜ axios ์š”์ฒญ์ด ์žˆ๋‹ค๊ณ  ๊ฐ€์ •ํ•ด ๋ด…์‹œ๋‹ค. 

axios
  .get('foo.example')
  .then((response) => {})
  .catch((error) => {
    console.log(error); //Logs a string: Error: Request failed with status code 404
  });

๋‹ค์Œ์˜ ๋ฐฉ๋ฒ•์œผ๋กœ console.log ๋กœ ์ฐ์–ด๋ณผ ๊ฒฝ์šฐ ๋‹จ์ˆœ string ๋งŒ ๋ฐ˜ํ™˜ํ•˜๊ฒŒ ๋ฉ๋‹ˆ๋‹ค. return ๋œ object๋ฅผ ๋ฐ›๊ณ  ์‹ถ์„ ๊ฒฝ์šฐ ์–ด๋–ป๊ฒŒ ํ•ด์•ผ ํ• ๊นŒ์š”? 

How to solve the problem

axios.get('/foo')
  .catch(function (error) {
    if (error.response) {
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    }
  });

์„œ๋ฒ„์—์„œ ์‘๋‹ต์„ ๋ฐ›์€ ๊ฒฝ์šฐ error ๊ฐ์ฒด์—๋Š” response ์†์„ฑ์ด ํฌํ•จ๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ ์œ„์™€ ๊ฐ™์ด ๊ฐ์ฒด๋ฅผ ๋ฐ›์œผ๋ฉด status code ๋ฅผ ๋ฐ›์•„์˜ฌ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. 


https://stackoverflow.com/questions/39153080/how-can-i-get-the-status-code-from-an-http-error-in-axios

๋ฐ˜์‘ํ˜•