johnson23
johnson23

Reputation: 296

Break axios promise chain on catch()

I've centralized all my API calls in a unique file API.js as below:

API.js

Class APIContextProvider extends Component {

    async apiCallTest() {

        var url = random_url

        const options = {
            url: url,
            method: 'GET',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json;',
            },
        };

        return await axios(options)
            .then(response => {
                if (response.status === 200) {
                    return response.data
                }
            }).catch(error => {
                console.log(error.response.status)
            }
        );;
    }

Then I call my API from another component:

OutsideClass.js

async componentDidMount() {
    this.context.apiCallTest().then(data => {
        // How can I prevent this then() to run when catch() happens?
    });
}

The order is which everything is done is: then().catch().then().

What I want is to prevent the last then(). from happening if a specific error is caught (like 401) since I want global error handling.

Looked everywhere but can't find a solution...

Thank you!

Upvotes: 0

Views: 1164

Answers (2)

M.D
M.D

Reputation: 280

If you want to catch exception globally, then use axios interceptors in your bootstrap file just after

window.axios = require('axios'); 
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

axios.interceptors.response.use(
function (response) { 
    return response; 
},
function (error) {
    // handle error
    if (error.response.status === 422) 
        return error;        
    if (error.response.status === 401) 
        alert(error.response.status + ': ' + error.response.data.message);               
});

Upvotes: 1

hiddenuser.2524
hiddenuser.2524

Reputation: 4988

You can throw the error again in you catch, and it will avoid the then and go to the next catch.

await axios(options)
            .then(response => {
                if (response.status === 200) {
                    return response.data
                }
            }).catch(error => {
                if (error.response.status === 401) { 
                  throw error;
                }
                console.log(error.response.status)
            }

Upvotes: 1

Related Questions