Vue.js Vue,使用axios调用时如何处理错误

Vue.js Vue,使用axios调用时如何处理错误,vue.js,error-handling,vuejs2,axios,Vue.js,Error Handling,Vuejs2,Axios,我正在尝试解决如何处理使用axios时的错误。请参阅下面的代码: //Admin.vue methods: { saveClicked: function(){ updateConfig(this.editedConfig) .then(response => { console.log("in here"); console.log(response); this.info.showAle

我正在尝试解决如何处理使用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
检查下图:


我遗漏了什么?

问题:为什么要添加:

   .then(response => response)
   .catch(error => error);
在你的
network.js
文件中

我猜你对承诺有些误解

API将返回另一个承诺。这一新的承诺既可以作为一种成功的方式,也可以作为一种例外的方式

API将返回另一个承诺。这个新的承诺有点不同。从文档:

如果onRejected抛出错误或返回本身被拒绝的承诺,则catch()返回的承诺将被拒绝;否则,问题就解决了

因此,在您的情况下,它将从下一次
调用中调用
resolve
,然后调用
。除非在
network.js
文件中抛出错误,这是毫无意义的


删除
network.js
文件中的2行,您将有您想要的行为。

问题:为什么添加:

   .then(response => response)
   .catch(error => error);
在你的
network.js
文件中

我猜你对承诺有些误解

API将返回另一个承诺。这一新的承诺既可以作为一种成功的方式,也可以作为一种例外的方式

API将返回另一个承诺。这个新的承诺有点不同。从文档:

如果onRejected抛出错误或返回本身被拒绝的承诺,则catch()返回的承诺将被拒绝;否则,问题就解决了

因此,在您的情况下,它将从下一次
调用中调用
resolve
,然后调用
。除非在
network.js
文件中抛出错误,这是毫无意义的

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