Vue method unable to catch error thrown by Axios promise

Having trouble catching an error in a Vue method called getTodo?
To see the issue, click on Set incorrect url and then on Get Todo. You will notice an error in the store as expected, but when the getTodo promise's then is executed in Vue, there's no error. However, if you select Set correct url, everything works fine. The console logs should display:

Error on store  
Error on vue

Check out the JavaScript and HTML code below:

const store = new Vuex.Store({
    state: {
        todo: '',
        msg: '',
        url: 'https://jsonplaceholder.typicode.com/todos/test',
        correct: false
    },
    mutations: { 
        // mutation logic here
    },
    actions: { 
        // action logic here
    }
})
new Vue({
    el: '#app',
    data: {
        // data definition here
    },
    computed: { 
        // computed properties here
    },
    methods: {
        // methods definition here
    }
})
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>
    <div id="app">
        <p>{{ message }}</p>
        <p>{{ todo }}</p>
        <p>Correct url: {{ correctUrl }}</p>
        <button @click="getTodo">Get Todo</button>
        <button @click="setCorrect">Set correct url</button>
        <button @click="setIncorrect">Set incorrect url</button>
    </div>
    
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="225457475a62110c0e100b">[email protected]</a>/dist/vuex.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</body>

</html>

Answer №1

Make sure to throw the error again after catching it in your getTodo action ..

actions: {
        getTodo({ state, commit }) {
            return axios.get(state.url)
                .then(response => {
                    console.log('success on store');
                    commit('setMsg', 'success on store');
                    commit('setTodo', response.data);
                })
                .catch(error => {
                    console.log('error on store');
                    commit('setMsg', 'error on store');
                    throw error;
                });
        }
}

const store = new Vuex.Store({
    state: {
        todo: '',
        msg: '',
        url: 'https://jsonplaceholder.typicode.com/todos/test',
        correct: false
    },
    mutations: {
        setTodo(state, payload) {
            state.todo = payload;
        },
        setMsg(state, payload) {
            state.msg = payload;
        },
        setCorrect(state) {
            state.url = 'https://jsonplaceholder.typicode.com/todos/1';
            state.correct = true;
        },
        setIncorrect(state) {
            state.url = 'https://jsonplaceholder.typicode.com/todos/test';
            state.correct = false;
        }
    },
    actions: {
        getTodo({ state, commit }) {
            return axios.get(state.url)
                .then(response => {
                    console.log('success on store');
                    commit('setMsg', 'success on store');
                    commit('setTodo', response.data);
                })
                .catch(error => {
                    console.log('error on store');
                    commit('setMsg', 'error on store');
                    throw error;
                });
        }
    }
})
new Vue({
    el: '#app',
    data: {
        message: ''
    },
    computed: {
        todo() {
            return store.state.todo;
        },
        msg() {
            return store.state.msg;
        },
        correctUrl() {
            return store.state.correct;
        }
    },
    methods: {
        getTodo() {
            store.dispatch('getTodo').then(() => {
                console.log('success on vue');
                this.message = 'success on vue'
            }).catch((e) => {
                console.log('error on vue');
                this.message = 'error on vue';
            });
        },
        setCorrect() {
            store.commit('setCorrect');
        },
        setIncorrect() {
            store.commit('setIncorrect');
        }
    }
})
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>
    <div id="app">
        <p>{{ message }}</p>
        <p>{{ todo }}</p>
        <p>Correct url: {{ correctUrl }}</p>
        <button @click="getTodo">Get Todo</button>
        <button @click="setCorrect">Set correct url</button>
        <button @click="setIncorrect">Set incorrect url</button>
    </div>
    
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b2c4c7d7caf2819c829c83">[email protected]</a>/dist/vuex.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</body>

</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exclude crypto-browserify from the NextJS build process

I have been dedicated to minimizing the build size of my app as much as possible, and I have observed that the crypto-browserify module is consuming a significant amount of space. While I understand that Next.js polyfills the node module if necessary, I wo ...

Sending properties to a Vue 3 composable does not result in reactivity

Having an issue where I am attempting to pass a component prop to a composable, but the computed function within the composable is not being called when the prop changes. import { toRefs } from 'vue'; export default { props: { aProp: Strin ...

retrieve the variable contained within the callback function

const axios = require('axios'); const options = { url: 'https://api.github.com/repos/axios/axios', headers: { 'User-Agent': 'axios' } }; function handleResponse(error, response, body) { if (!error && re ...

Ways to apply the .not selector efficiently in jQuery

I have a situation with two separate divs, one named task1 and the other named task2. Each of these tasks contains panels with various names. Within task2, there is a duplicate name (Greg), who also belongs to the duplicate class. I'm trying to figure ...

How to retrieve values from Vue custom renderer's variable

I have been experimenting with implementing a custom renderer for the Vue Word Cloud component within Laravel. You can find the component here: https://github.com/SeregPie/VueWordCloud Initially, I prepare my word array using PHP (which is functioning co ...

Selected jQuery plugin is not updating HTML select option

I've been attempting to update the select tag in my HTML file to match the style used in the example on the Chosen v1.8.7 website, but despite following the instructions, the select element remains unchanged: test.html <head> <link rel=& ...

Storing a JSON data structure in a file in Node.js

I have searched for similar questions on this topic but have not found a solution. My task involves converting a CSV xml file to a json array of objects. The function provided below successfully accomplishes this: const csvtojsonV2 = require("csvtojson" ...

The Next Js version "next" is at "14.2.3", indicating that the page is experiencing issues

After creating a project in Next.js version "14.2.3", I encountered this page with an error message. Surprisingly, I hadn't made any changes to my code when this occurred. https://i.sstatic.net/UcTnF3ED.png What could be the reason for this sudden i ...

Deleting text after an answer has been given using jQuery or JavaScript

I seem to have encountered a problem with the logic I've implemented. The desired functionality is for the user to enter an answer to the question presented. Upon submitting the answer, the current text (first question) should disappear and the next q ...

What causes the behavior of Node.js to be the way it is?

Check out this code snippet function removePrototype() { var obj = {}; for (var _i = 0, _a = Object.getOwnPropertyNames(obj.__proto__); _i < _a.length; _i++) { var prop = _a[_i]; obj[prop] = undefined; } obj.__proto__ = ...

Is there a way to extract the Date property from a JSON string using the new Date() method?

Is there a way to extract the MyDate property as an actual Date object after parsing? var myObject = JSON.parse('{ "MyDate" : new Date ("2013-12-13"), "Test" : "TestString"}'); I am dealing with a large file containing thousands of records in J ...

Retrieving Remote Headers in Loopback.io Inbound HTTP Method

In my remote method, I have placed the application logic as shown below: module.exports = function(Entity) { HcpEntity.retrieveProfile = function(body, cb) { process.nextTick(function() { //TODO: Add Application Logic here } } } Also, he ...

What steps can I take to stop the mui TreeView component from intercepting events intended for another component?

Within my application, I have implemented a TreeView component that is displayed alongside an Options component containing two buttons. return ( <div style={{ display: "flex", flexDirection: "column", height: ...

Error: Attempting to access the 'createClient' property of an undefined object - TypeError

Recently, I've been working on a project where I needed to create and store a session in redis. To achieve this, I referred to the API documentation provided by this GitHub repository https://github.com/tj/connect-redis. However, I encountered an iss ...

Issues with the creation of an AngularJS table are causing functionality to malfunction

2021 UPDATE: Note: This question was drafted when I was still learning HTML and JS. If you are seeking assistance for an issue, this might not be very useful as my code was messy. Sorry for any inconvenience caused. The question will remain posted in acco ...

Is there a way to automatically adjust the size of a textarea when closing a popup modal?

There's a form in my popup modal. Whenever I resize the textarea and then close the modal, upon reopening it, the textarea isn't in its proper form anymore. I'm looking for a way to reset the size of the textarea. Any assistance on this matt ...

How can I transfer information from an HTML file (using the ejs template engine) to Node.js?

Currently, I am working on my own project using a combination of Node.Js (Express), MongoDB, JavaScript/jQuery, and HTML with EJS as the template engine. So far, I have some understanding of how to send data from the Node.js router to views and how to sen ...

Text-color in the v-tooltip

Is there a way to change the text color of v-tooltips components without affecting the tooltip background color? I attempted to inspect the element, but the tooltip only appears on hover, making it impossible to inspect. Below is the code snippet: < ...

Creating fixed-size arrays within a Mongoose schema is a commonly sought after feature that allows

For a specific scenario where I have example input: [[1,2],[3,2],[1,3],...,[4,5]] I am wondering about the correct way to define a model schema in mongoose. Here is my initial Schema: const SubproductSchema = new Schema({ ... positions: [{ type: ...

Adding a conditional to target a bootstrap modal in AngularJS

I am facing a situation where I need a modal to only appear when specific conditions defined in my controller are met, rather than every time a button is clicked. Here's the HTML CODE: <button class="btn btn-primary-outline" type="button" data-uk ...