【问题标题】:handle response with status different than 200 with Asyn/Await and axios in vuejs在 vuejs 中使用 Async/Await 和 axios 处理状态不同于 200 的响应
【发布时间】:2019-02-22 22:18:04
【问题描述】:

我正在开发一个网站,该网站在异步等待函数中使用 axios 发出请求,如下所示:

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

一切正常,但我不知道如何处理具有特定状态的错误(例如,当响应状态为 400 时显示特定消息)。我尝试使用 e.status,但它不起作用,所以,我不知道要调用什么来获取请求的状态。我还尝试了带有 response.status 的 try 函数,我知道它会以 400 状态响应,但它也不起作用。仅当 response.status 为 200 时才有效。

【问题讨论】:

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


    【解决方案1】:

    使用error.response.status:

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

    【讨论】:

      猜你喜欢
      • 2020-09-10
      • 2018-09-14
      • 2021-05-10
      • 2021-09-11
      • 1970-01-01
      • 2020-11-19
      • 1970-01-01
      • 2018-03-31
      • 1970-01-01
      相关资源
      最近更新 更多