handle response with status different than 200 with Asyn/Await and axios in vuejs

时间:2018-09-18 20:16:27

标签: javascript vue.js ecmascript-6 async-await axios

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.

1 个答案:

答案 0 :(得分:1)

Use error.response.status:

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