Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axios 400 error request call then instead of catch

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

like image 539
50l3r Avatar asked Dec 06 '17 16:12

50l3r


People also ask

Why does Axios throw error on 400?

By default, the axios HTTP library throws an error anytime the destination server responds with a 4XX / 5XX error (for example, a 400 Bad Request ). Since axios raises an error, your workflow will stop at this step.

How do you catch errors on Axios?

A conventional approach is to catch errors in the catch() block like below: axios. get('/api/xyz/abcd') . catch(function (error) { if (error.


2 Answers

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

like image 87
50l3r Avatar answered Oct 17 '22 07:10

50l3r


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);
  });
like image 22
Amaarrockz Avatar answered Oct 17 '22 06:10

Amaarrockz