0

I am trying to work out on how to handle errors when using axios. Please see the code below:

//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);
}

When the requests is successful, everything is fine. I get my alert saying all is good.

I forced my backend to return an error for every request so i can simulate error behaviour in my Vue application and this is what i observed:

Even when error is received. The the program is going through then() in Admin.vuecheck the image below:

enter image description here

What have i missed?

1 Answer 1

4

Question: Why did you added:

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

in your network.js file?

I guess You have some misunderstanding of Promise.

From the API Promise.prototype.then will return an other promise. This new Promise will serve either as a way to compose something to do on success or catch exception.

From the API Promise.prototype.catch will return an other promise. This new Promise is a bit different. From the doc:

The Promise returned by catch() is rejected if onRejected throws an error or returns a Promise which is itself rejected; otherwise, it is resolved.

So in your case it will call the resolve from the next then call. Unless you throw error in the network.js file which is pointless.

Remove the 2 line in the network.js file and you will have your intended behaviour.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.