22

I have this function:

add(App, Params, Callback){
    var self = this;

    var Data = self.process_fields(Params)

    self.$http.post(
        paths.api + '/app/' + App.Permalink,
        new URLSearchParams(Data)
    ).then(function (error, response) {
        console.log("then");
        if (typeof (Callback) == "function") {
            Callback(true, response.data.data);
        }
    }).catch(function(error){
        console.log("catch");
        if(typeof error.response !== "undefined"){
            errors.render(error.response.data.error)
        }

        if (typeof (Callback) == "function") {
            Callback(false, null);
        }
    });
}

When i call request and recieve a 400 error, it calls then instead of catch:

enter image description here

50l3r
  • 1,549
  • 4
  • 16
  • 27

3 Answers3

51

I found the solution

Problem caused by dont return promise in axios interceptors:

axios.interceptors.response.use((response) => {
    return response;
}, (error) => {
    if (!error.response) {
        alert('NETWORK ERROR')
    } else {
        const code = error.response.status
        const response = error.response.data
        const originalRequest = error.config;

        if (code === 401 && !originalRequest._retry) {
            originalRequest._retry = true

            auth.commit('logout');
            window.location.href = "/login";
        }

        return Promise.reject(error)
    }
});

adding return Promise.reject(error) works like a charm

50l3r
  • 1,549
  • 4
  • 16
  • 27
  • It would be nice to just copy and paste your code, but the reality is that I've no idea what you're doing. Why are you checking for no response? Why are you checking exactly for the `401` status code? Why are you setting the `_retry` variable? – Christian Vincenzo Traina Jun 26 '23 at 14:49
5

This is on purpose in older version of Axios.

validateStatus has been added into config since v0.11. We can use this option to specify valid status code range. By default, valid code is >= 200 and < 300.

validateStatus: function (status) {
  return status >= 200 && status < 300; // default
},

Ref: https://github.com/axios/axios/issues/41#issuecomment-215100137

osk2
  • 329
  • 3
  • 9
3

Add a response interceptor like

axios.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
  }, function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  });
Amaarockz
  • 4,348
  • 2
  • 9
  • 27