javascript - handle response with status different than 200 with AsynAwait and axios in vuejs - Stack Overflow

I'm working on a website that has a request made with axios inside an async await function that lo

I'm working on a website that has a request made with axios inside an async await function that looks like this:

async function () {
  try {
    const response = await axios.get('requestUrl')
  } catch (e) {
    throw new Error(e)
  }
}

Everything works fine, but I don't know how to handle errors with a specific status (for example displaying a specific message when the response status is 400). I tried with e.status, but it doesn't work, so, I don't know what to call in order to get the status of the request. I also tried in the try function with response.status in a moment I knew it would respond with a 400 status, but it didn't work either. It just works when the response.status is 200.

I'm working on a website that has a request made with axios inside an async await function that looks like this:

async function () {
  try {
    const response = await axios.get('requestUrl')
  } catch (e) {
    throw new Error(e)
  }
}

Everything works fine, but I don't know how to handle errors with a specific status (for example displaying a specific message when the response status is 400). I tried with e.status, but it doesn't work, so, I don't know what to call in order to get the status of the request. I also tried in the try function with response.status in a moment I knew it would respond with a 400 status, but it didn't work either. It just works when the response.status is 200.

Share Improve this question edited Sep 18, 2018 at 20:34 Carlos Pisarello asked Sep 18, 2018 at 20:16 Carlos PisarelloCarlos Pisarello 1,2846 gold badges23 silver badges41 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

Use error.response.status:

async function () {
  try {
    const response = await axios.get('requestUrl')
  } catch (e) {
    if (e.response.status === 400) {
      // ...
    } else {
      // ...
    }
  }
}

Code written in typescript:

try {
  const response = await axios.get('requestUrl')
}
catch (e) {
  const axiosErr = e as AxiosError
  const status = axiosErr.response ? axiosErr.response.status : 0
  if (status === 400) {
    // ...
  } else {
    // ...
  }
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742251887a4409308.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信