【问题标题】:Vue, how to handle errors when using axios callsVue,使用axios调用时如何处理错误
【发布时间】:2019-01-10 11:01:19
【问题描述】:

我正在尝试研究如何在使用 axios 时处理错误。请看下面的代码:

//Admin.vue

methods: {
    saveClicked: function(){

      updateConfig(this.editedConfig)
        .then(response => {
          console.log("in here");
          console.log(response);
          this.info.showAlert = true;
          this.info.message = "Successfully updated config!!"
          this.info.alertType = "success";
          this.showJsonEditor = !this.showJsonEditor;

        })
        .catch(error => {
          this.info.showAlert = true;
          this.info.message = "Failed to update config, please try again later"
          this.info.alertType = "error";
        });
    }
}

//network.js

function updateConfig(editedConfig){

  return axios.put(URL,editedConfig, {
    headers: {
      "Content-type": "application/json"
    }
  })
      .then(response => response)
      .catch(error => error);
}

请求成功后,一切正常。我收到警报说一切都很好。

我强迫我的后端为每个请求返回一个错误,这样我就可以在我的 Vue 应用程序中模拟错误行为,这就是我观察到的:

即使收到错误消息。该程序正在通过then()Admin.vue查看下图:

我错过了什么?

【问题讨论】:

    标签: vue.js error-handling vuejs2 axios


    【解决方案1】:

    问题:为什么要添加:

       .then(response => response)
       .catch(error => error);
    

    在您的network.js 文件中?

    我猜你对 Promise 有一些误解。

    来自 API Promise.prototype.then 将返回另一个承诺。这个新的 Promise 将作为一种方式来组合成功后要做的事情或捕获异常。

    从 API Promise.prototype.catch 将返回另一个承诺。这个new Promise 有点不同。来自文档:

    如果 onRejected 抛出错误或返回一个本身被拒绝的 Promise,则 catch() 返回的 Promise 被拒绝;否则就解决了。

    因此,在您的情况下,它将从下一个 then 调用中调用 resolve。除非您在 network.js 文件中抛出错误,否则毫无意义。

    删除network.js 文件中的第 2 行,您将获得预期的行为。

    【讨论】:

      猜你喜欢
      • 2020-11-19
      • 2020-08-20
      • 1970-01-01
      • 1970-01-01
      • 2018-10-02
      • 2020-05-13
      • 2019-03-04
      相关资源
      最近更新 更多