Axios - Prevent .then() from executing on http errors











up vote
2
down vote

favorite












My problem:



I have set up an interceptor to catch error codes in HTTP responses.
When the JWT expires, I have a code 401 coming back from the server. Here's my interceptor:



this.axios.interceptors.response.use(undefined, (error) => {
if (error.response.status === 401) {
this.$store.dispatch('auth/logout').then(() => {
this.$router.push({name: 'login'})
return Promise.reject(error)
})
}
})


My interceptor works fine, except the request that is being intercepted still resolves into the .then() part.



this.axios.get('/texts').then(function(){
// This is still being executed and generates javascript errors because the response doesn't contain the right data
})


From the axios documentation, I found out you can prevent this by calling



this.axios.get('/texts').then(function(){
// only on success
}).catch(function(){
// only on errors
}).then(function(){
// always executed
})


But this is pretty verbose and I don't want to do this on every request that my app makes.



My question is:



How do I prevent axios from executing the .then() callback when I have an error. Is it something I can do in the interceptor? Like event.stopPropagation() or something like that?










share|improve this question






















  • "this is pretty verbose" Maybe... But that's how you do it. If you're looking for a less verbose syntax then consider using async/await (and a transpiler if required).
    – spender
    12 hours ago















up vote
2
down vote

favorite












My problem:



I have set up an interceptor to catch error codes in HTTP responses.
When the JWT expires, I have a code 401 coming back from the server. Here's my interceptor:



this.axios.interceptors.response.use(undefined, (error) => {
if (error.response.status === 401) {
this.$store.dispatch('auth/logout').then(() => {
this.$router.push({name: 'login'})
return Promise.reject(error)
})
}
})


My interceptor works fine, except the request that is being intercepted still resolves into the .then() part.



this.axios.get('/texts').then(function(){
// This is still being executed and generates javascript errors because the response doesn't contain the right data
})


From the axios documentation, I found out you can prevent this by calling



this.axios.get('/texts').then(function(){
// only on success
}).catch(function(){
// only on errors
}).then(function(){
// always executed
})


But this is pretty verbose and I don't want to do this on every request that my app makes.



My question is:



How do I prevent axios from executing the .then() callback when I have an error. Is it something I can do in the interceptor? Like event.stopPropagation() or something like that?










share|improve this question






















  • "this is pretty verbose" Maybe... But that's how you do it. If you're looking for a less verbose syntax then consider using async/await (and a transpiler if required).
    – spender
    12 hours ago













up vote
2
down vote

favorite









up vote
2
down vote

favorite











My problem:



I have set up an interceptor to catch error codes in HTTP responses.
When the JWT expires, I have a code 401 coming back from the server. Here's my interceptor:



this.axios.interceptors.response.use(undefined, (error) => {
if (error.response.status === 401) {
this.$store.dispatch('auth/logout').then(() => {
this.$router.push({name: 'login'})
return Promise.reject(error)
})
}
})


My interceptor works fine, except the request that is being intercepted still resolves into the .then() part.



this.axios.get('/texts').then(function(){
// This is still being executed and generates javascript errors because the response doesn't contain the right data
})


From the axios documentation, I found out you can prevent this by calling



this.axios.get('/texts').then(function(){
// only on success
}).catch(function(){
// only on errors
}).then(function(){
// always executed
})


But this is pretty verbose and I don't want to do this on every request that my app makes.



My question is:



How do I prevent axios from executing the .then() callback when I have an error. Is it something I can do in the interceptor? Like event.stopPropagation() or something like that?










share|improve this question













My problem:



I have set up an interceptor to catch error codes in HTTP responses.
When the JWT expires, I have a code 401 coming back from the server. Here's my interceptor:



this.axios.interceptors.response.use(undefined, (error) => {
if (error.response.status === 401) {
this.$store.dispatch('auth/logout').then(() => {
this.$router.push({name: 'login'})
return Promise.reject(error)
})
}
})


My interceptor works fine, except the request that is being intercepted still resolves into the .then() part.



this.axios.get('/texts').then(function(){
// This is still being executed and generates javascript errors because the response doesn't contain the right data
})


From the axios documentation, I found out you can prevent this by calling



this.axios.get('/texts').then(function(){
// only on success
}).catch(function(){
// only on errors
}).then(function(){
// always executed
})


But this is pretty verbose and I don't want to do this on every request that my app makes.



My question is:



How do I prevent axios from executing the .then() callback when I have an error. Is it something I can do in the interceptor? Like event.stopPropagation() or something like that?







javascript promise axios interceptor






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 12 hours ago









MonsieurNinja

87821227




87821227












  • "this is pretty verbose" Maybe... But that's how you do it. If you're looking for a less verbose syntax then consider using async/await (and a transpiler if required).
    – spender
    12 hours ago


















  • "this is pretty verbose" Maybe... But that's how you do it. If you're looking for a less verbose syntax then consider using async/await (and a transpiler if required).
    – spender
    12 hours ago
















"this is pretty verbose" Maybe... But that's how you do it. If you're looking for a less verbose syntax then consider using async/await (and a transpiler if required).
– spender
12 hours ago




"this is pretty verbose" Maybe... But that's how you do it. If you're looking for a less verbose syntax then consider using async/await (and a transpiler if required).
– spender
12 hours ago












1 Answer
1






active

oldest

votes

















up vote
0
down vote













Did you try catch in the end of the chain? You will get following



this.axios.get('/texts').then(function(){
// only on success
}).then(function(){
// only on success in previous then
}).catch(function(){
// executes on every error from `get` and from two previous `then`
})





share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














     

    draft saved


    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53371873%2faxios-prevent-then-from-executing-on-http-errors%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote













    Did you try catch in the end of the chain? You will get following



    this.axios.get('/texts').then(function(){
    // only on success
    }).then(function(){
    // only on success in previous then
    }).catch(function(){
    // executes on every error from `get` and from two previous `then`
    })





    share|improve this answer

























      up vote
      0
      down vote













      Did you try catch in the end of the chain? You will get following



      this.axios.get('/texts').then(function(){
      // only on success
      }).then(function(){
      // only on success in previous then
      }).catch(function(){
      // executes on every error from `get` and from two previous `then`
      })





      share|improve this answer























        up vote
        0
        down vote










        up vote
        0
        down vote









        Did you try catch in the end of the chain? You will get following



        this.axios.get('/texts').then(function(){
        // only on success
        }).then(function(){
        // only on success in previous then
        }).catch(function(){
        // executes on every error from `get` and from two previous `then`
        })





        share|improve this answer












        Did you try catch in the end of the chain? You will get following



        this.axios.get('/texts').then(function(){
        // only on success
        }).then(function(){
        // only on success in previous then
        }).catch(function(){
        // executes on every error from `get` and from two previous `then`
        })






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 12 hours ago









        Anonym

        264




        264






























             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53371873%2faxios-prevent-then-from-executing-on-http-errors%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

            SQL update select statement

            'app-layout' is not a known element: how to share Component with different Modules