Dealing with error handling in NUXT using asyncData and Vue actions

The URL I am trying to access is

http://mywebsite.com/[category that doesn't exist]
. Despite the code snippet provided below, I am unable to reach the catch block in asyncData.

async asyncData({ params, store }) {
  try { 
    await store.dispatch('categories/GET_CATEGORIES')
    await store.dispatch('products/GET_products', params.category)
  } catch(e) {
    console.log(e) // no output in the console
  }
}

This is how the Vuex action looks like:

async GET_PRODUCTS({commit}, category) {
  try {
    let url
    if (!category) {
      url = 'some url'
    } else {
      url = 'some other url'
    }

    const response = await this.$axios.$get(url)

    if (!response.length) throw new Error()
    
    commit('some mutation', response.data)
  } catch(e) {
    console.log(e)
  }
}

If an error is thrown, shouldn't it trigger the catch block in asyncData? My intention behind this is to utilize the router for redirecting to the home page upon encountering an error in the action logic.

I have come across limited information regarding directly integrating routing into Vuex (possibly not a good practice?). Nevertheless, asyncData provides access to the context object which contains the router.

Answer №1

Your current approach includes error detection and suppression.

If you want the calling function to handle the error, consider throwing the error back within your logic:

async GET_PRODUCTS({commit}, category) {
  try {
    //...
    const response = await this.$axios.$get(url)

  } catch(e) {
    // perform actions based on the error here...

    // then throw the error again
    throw e
  }
}

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

jQuerry's on method fails to respond to newly added elements through the clone() function

I always thought that jquery's on() function would handle events for dynamically added elements in the DOM, such as those added via ajax or cloning. However, I'm finding that it only works for elements already attached to the dom at page load. Cl ...

Poor quality picture captured with the use of the getUserMedia() Javascript function

Is there a way to improve the resolution of mobile phone camera screenshots taken with JavaScript's getUserMedia function? if (navigator.mediaDevices) { navigator.mediaDevices.getUserMedia({ video: { width: { min: 1280, }, heig ...

Row within a table displaying link-like behavior

Here is the code I'm currently using: $('.table-striped tr').click( function() { var link = $(this).find('a').attr('href'); if(link != 'undefined') { window.location = link; } }).hover( func ...

Cordova does not support the transform property

In the process of creating an Apache Cordova app using the Ionic framework and working with Phonegap Build, I encountered a challenge. The main page of my app features rows of icons that appear like this: However, there is a problem on Android 4.4.x and o ...

Creating a Webgrid in MVC and integrating it with a custom class in AngularJS

Hey there, I'm a beginner when it comes to AngularJS and I'm looking to bind the webgrid within the method of AngularJS. $scope.SaveDetails = function () { debugger; var UserID = '@Session["ID"]'; ...

Obtain the index by clicking on an element within an HTMLCollection

Within my HTML code, I have 9 <div> elements with the class ".square". I am looking to make these divs clickable in order to track how many times each one is clicked and store that information in an array. For example, if the fifth <div> is c ...

Error Alert: The combination of React and Redux-router is causing an unexpected issue. The reducer is expected to be a

Whenever I make a coding mistake and encounter a runtime error, the error reporting is not very helpful. For example, when I mistakenly typed Date() instead of new Date(), the error message I received was... Uncaught Error: Expected the reducer to be a fu ...

Issue with component not properly reflecting changes made to array

I recently started using Vue and came across an interesting behavior that I wanted to clarify. I have a component that receives a list of facets and organizes them for display purposes. Here is a snippet of the code: // Code snippet The above code showcas ...

When attempting to access /test.html, Node.js server returns a "Cannot GET"

Embarking on the journey of diving into Pro AngularJS, I have reached a point where setting up the development environment is crucial. This involves creating an 'angularjs' directory and placing a 'test.html' file in it. Additionally, o ...

Incorporating a dynamic URL within a script tag with AngularJs

I am currently integrating a payment gateway into my Single Page Application (SPA) using AngularJS. The issue I'm facing is that the payment gateway requires me to include a script with a specific ID for the payment process to work correctly. This i ...

The `required` attribute is ineffective when used with the `<form>` element

My required attribute isn't enforcing mandatory field completion before form submission. HTML Code: <!-- Modal Content --> <form class="modal-content2"> <div class="container3"> < ...

"Emphasizing the Html.ActionLink menu for improved user navigation and

Currently, I am facing an issue with my menu. I want to clear previously visited links while keeping the current one styled as a:visited in CSS. Although I have attempted to achieve this, unfortunately, the code is not functioning properly. Here is what I ...

Can you provide guidance on integrating stylus-resources-loader with Vue CLI 3?

It seems like modifying vue.config.js is the key to achieving my desired configuration. However, I've encountered issues when directly pasting the desired config into the configureWebpack object. Has anyone else successfully solved this problem? Here ...

Locate the generated ID of the inserted child when saving the parent in MongoDB

If I have a document representing a post with comments like the one below: { "_id": "579a2a71f7b5455c28a7abcb", "title": "post 1", "link": "www.link1.com", "__v": 0, "comments": [ { "author": "Andy", "body": "Wis ...

Access your Vue.js application using Google Sign-In (GIS)

Having trouble with the discontinuation of gapi.oauth2 by Google and finding the new Sign in With Google tools confusing. Project Structure Looking to implement user sign-in with Google on my Vue frontend and authenticate them using OIDC server flow on ...

The jQuery target is not able to locate the specified element

Why does this code snippet work in one case: jQuery(this).closest("li").find("p").text(); But when enclosed within a function, it fails to produce the desired result: jQuery.each(words, function(i, v) { jQuery(this).closest("li").find("p").text(); } ...

Tips on altering the input content in React Js?

I am currently working on developing a component for my application where I want to create a button that, when clicked, opens an input field. After entering text into the input field and clicking the button again, another input field should appear, and so ...

Converting a 3D model from Unity to three.js for seamless integration

I am tasked with building a human body model in WebGL using three.js, but I only have a Unity model. Is there a way to export the Unity model as an object or something similar for this purpose? ...

Utilizing the dollar shorthand for jQuery in conjunction with Selenium

While utilizing the Selenium addon along with jQuery in my project, I encountered an issue where the use of jQuery functions containing $ in Selenium would trigger a "function not found" error. The problem was resolved by removing jQuery, but using jQuer ...

Button click triggers CSS animation

Check out the interactive demo $(document).ready(function(){ $('#btn-animate').click(function(){ animate(); }); $('#btn-remove').click(function(){ $('.to-animate').removeClass('animate'); }); func ...