Prevent handling errors in Vue when Axios receives a response for every request

In my project, I utilize axios interceptors to manage various errors, particularly those without a response. However, I rely on the error.response.data message for validations and displaying messages stored in the backend in certain areas of the project. Despite this interceptor, I still need to check if the error has a response.

This is how my interceptor is set up:

axios.interceptors.response.use(
    function (response) {
      ...
    },
    function (error) {
      if (!error.response) {
        ...
        return Promise.reject(new Error(error.message))
      }

An instance where I specifically need error.response for a request is:

this.$store.dispatch('updateField', { [this.fieldKey]: this.value ? this.value : null }).catch((error) => {
        this.validateField(error.response.data)
      })

To prevent an error in the console, I am forced to place the validateField call inside an if(error.response). Is there a better solution than scattering this conditional throughout my code?

Answer №1

response may not always be required, as it is optional:

this.validateField(error.response?.data)

An alternative approach is to create a normalized error in an interceptor that includes necessary properties and does not rely on the Axios error structure:

function (rawError) {
  const error = new Error(error.response?.data?.myError || error.message);
  error.data = error.response?.data || null;
  error.headers = error.response?.headers || null;
  error.status = error.response?.status || 0;
  return Promise.reject(error);
}

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

Troubleshooting: Unable to mutate a state variable in Vuex

I am working on updating my contact list whenever a different brand is selected. The goal is to clear the array of contacts associated with the current brand and then refill it with the new brand's contacts. However, I'm facing an issue in my Vu ...

The inner workings of Virtual DOM in React and Vue disclosed

I am a student experimenting with creating my own Virtual DOM for a college project in JavaScript, keeping it simple without advanced features like props or events found in popular frameworks like React and Vue. I'm curious about code splitting. If I ...

Using Ajax to insert data into WordPress

Looking to incorporate data into the WordPress database using Ajax integration. functions.php function addDataToDB(){ global $wpdb, $count; $count = 25; $wpdb->insert( 'custom_table', array( 'slid ...

How can I identify duplicate values within two distinct javascript objects?

Consider two sets of JavaScript arrays containing objects: var allUsers=[{name:"John",age:25},{name:"Emily", age:30},{name:"Michael",age:22}] and var activeUsers=[{name:"John",status:"active"},{name:"Sarah", status:"active"}] I am attempting to iterat ...

How can I align Javascript output vertically in the middle?

I am currently facing an issue with a JavaScript clock displaying in a narrow frame: <!DOCTYPE html> <HTML> <HEAD> <TITLE>Untitled</TITLE> <SCRIPT> function checkTime(i) { if (i < 10) { ...

Oops! The useNavigate() function can only be utilized within the confines of a <Router> component

I encountered an error while working on my project: An uncaught Error occurred: useNavigate() may only be used within a context of a <Router> component. at invariant (bundle.js:36570:20) at useNavigate (bundle.js:36914:35) at App (bundle. ...

Removing default headers in Axios for a single requestUpdate Axios to exclude default

I am having an issue with retrieving location data from the Google Maps API due to a CORS Policy Error caused by default headers in my bootstrap.js window.axios.defaults.headers.common = { 'X-Requested-With': 'XMLHttpRequest', & ...

A guide on updating data with Vue-SweetAlert2 by passing user input

I'm currently working on creating a "create" button that will prompt a popup with a text input field for the user, similar to the image below. https://i.sstatic.net/eP7ki.png The expected behavior is that when the OK button is clicked, the name ente ...

Encountering an issue while attempting to make changes and test a copied GitHub library - npm ERROR! version cannot be located

I'm new to the world of Github forking and pull requests. My goal is to fork a repository, make some changes, and test them out on a project before submitting a pull request. I've already forked the repository and made modifications, but I' ...

Utilize Ajax to display detailed product information within a modal using Django

In my application, the main purpose is to showcase a collection of furniture items on the homepage. Each furniture item has a quick preview button that, when clicked, should display detailed information about that specific item. I attempted to integrate aj ...

Generating radio buttons dynamically and automatically selecting the correct button using AngularJS

In the questionnaire form, each question is looped over along with its answers to create radio buttons for each answer. The answer object contains a property called answered, which can be true or false depending on whether the answer has been previously ...

directive for form validations is malfunctioning

I am a beginner with AngularJS and I'm currently working on writing a directive that wraps an input box inside a form tag, followed by a 'div' element which includes validation. Unfortunately, the validation is not functioning as expected. Y ...

Is it time to ditch daylight saving time - am I managing my dates and times correctly?

Currently, I am in the process of working on a PHP/mySQL web application where dates are stored as unix timestamps in columns that are UNSIGNED INT(10). When it comes to displaying these dates in the web view, we utilize moment.js to parse the numbers. On ...

Is it possible to prevent iPhone from resizing when the address bar is hidden or shown?

I am currently working on an unconventional website with a quirky design. It is meant to have a visually appealing layout with plenty of animations and full responsiveness. The main body element is set to overflow: hidden; and the structure is as follows: ...

Integrate JavaScript code with HTML pages

After creating a basic HTML structure that I am proud of, I encountered some challenges with getting the Javascript to function properly. I am new to working with Javascript and received some initial assistance, but unfortunately, it is no longer working. ...

Is the order of return guaranteed for Ajax requests?

This particular inquiry raises the question of whether Ajax requests follow the order in which they are sent. While it appears that Ajax requests may not always return in the same order they were dispatched, the use of the TCP protocol suggests that packet ...

Sign up for your own personalized Express and HBS helper now!

As a newcomer to Node, I appreciate your patience with me. I recently utilized the express generator module with the -hbs flag to switch from the default templating engine to Handlebars. Currently, I am attempting to register a custom helper to enable me ...

Transferring an ES6 class from Node.js to a browser environment

I've been exploring ways to bundle a super basic ES6-style class object for the browser. Here's an example: class Bar { constructor(){ this.title = "Bar"; } } module.exports = Bar; While I can easily utilize this in my node projec ...

Troubleshooting lack of output in Console.log (NodeJs)

I am facing an issue where I can't see any output when trying to console log a JavaScript code using Node.js. const pokemon = require('pokemon'); pokemon.all(); var name = pokemon.random(); console.log(name); I am unable to even display a ...

Can the roundabout be modified to display 5 elements in front instead of the usual 3?

I am currently utilizing the roundabout plugin to create an infinite slider that continuously loops. However, I am facing an issue where I would like to display 5 elements in a row instead of 3. Has anyone attempted this customization before? Here is my p ...