Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axios interceptor - error not returned to "then" method

Tags:

reactjs

axios

I call an api method, and when the response is 500 server error, the axios interceptor function starts, and returns Promise.reject(error);

But it stops there so the "then" function never runs. Instead it becomes "Uncaught":

Uncaught (in promise) Error: Request failed with status code 500

Shouldn't the interceptor return the error to the function which made the api call, and then I can handle the error there?

Here is code:

    //on submitting form
    onSubmit(data){

           //call api function
          api.sendPayment(data).then(response => {

                //this never runs
                 alert('response!')
                console.log(JSON.stringify(response))
            }    


    });


//Api function
sendPayment: (formData) => {

        return axios.post('/api/checkout', formData);
    },

//interceptor

axios.interceptors.response.use(response => {
    return response;
}, error => {

    //this executes the "uncaught" error instead of returning to the "then" function.
    return  Promise.reject(error);
});
like image 816
Galivan Avatar asked Jun 15 '26 05:06

Galivan


1 Answers

You need to use the .catch. Error won't caught in .then

api.sendPayment(data).then(response => {
    //this never runs
        alert('response!')
    console.log(JSON.stringify(response))
}).catch(err => {
    //Handle your error here
    console.log(err.response);
})
like image 130
Abin Thaha Avatar answered Jun 17 '26 19:06

Abin Thaha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!