Axios vuex обработка ошибок

I just use the catch. The same thing I was using before I switched to vuex. It’s probably the most universal and well documented solution and lets me continue to insert my errors into the html of the components like I was doing before. It also lets me continue to use my loading = true, loading = false html animation.

So I end up with 3 state properties, data, error, and loading. It seems to work for me. Your mileage may vary. I am also using vuex modules and namespacing but here is a simplified example without that

//somevuexstore.js

actions: {

fetchData(context) {

    axios
        .get("api/someendpoint")
        .then(response => {
            context.commit('loading')
            context.commit('organizations', response.data)

        }).catch(error => {
            console.log(error.response.data.message || error.message)
            context.commit('error', error)
        });
},

mutations: {
organizations(state, data) {
    return state.organization = data
},

error(state, data) {
    return state.error = data
},

loading(state) {
    return state.loading = false
},

state= {

organization: [],
error: '',
loading: true
}

Then in my component.vue it’s very similar to the way I was doing it before, just with the added computed properties.

computed: {
...mapState({
        getError: 'error',
        getLoading: 'loading',
        getAllOrg: 'organization',
}),
}

mounted() {
      this.$store.dispatch('fetchData')
}

And my html would be stuff like this.

<tr v-for="value in getAllOrg" :key="value.id">
   <td>{{ value.id }}</td>
   <td>{{ value.email }}</td>
   <td>{{ value.name }}</td>
   <td>{{ value.['created-at'] | formatDate }}</td>
</tr>

I insert the error messages where appropriate

<div v-if="getError" class="error">
   <p>{{ getError }}</p>
</div>

For loading animation I use vue spinners package inserted into html where appropriate.

<div v-if="getLoading" style="height:37px;">
    <p>
      <bar-loader class="custom-class" color="#c2c2c2" 
      getLoading="getLoading" 
      :width="130"></bar-loader>
   </p>

Error handling is a critical aspect of any application, and the same holds true for Vue.js applications. When using Vuex for state management and Axios for API requests, it can be challenging to handle errors effectively. Improper error handling can lead to unexpected behaviors and bugs, affecting the user experience and overall reliability of the application. In this guide, we will explore several best practices for error handling in Vue.js with Vuex and Axios.

Method 1: Centralized Error Handling with a Vuex Module

Handling errors in Vue.js can be a challenging task, especially when you are using Vuex and Axios. In this tutorial, we will discuss how to implement centralized error handling with a Vuex module in Vue.js.

Step 1: Create a Vuex Module for Error Handling

First, we need to create a Vuex module for error handling. We can create a new file error.js in the store directory and define the module as shown below:

const state = {
  error: null
}

const mutations = {
  setError(state, error) {
    state.error = error
  },
  clearError(state) {
    state.error = null
  }
}

const actions = {
  setError({ commit }, error) {
    commit('setError', error)
  },
  clearError({ commit }) {
    commit('clearError')
  }
}

export default {
  state,
  mutations,
  actions
}

In the above code, we have defined a state object that stores the error message. We have also defined two mutations to set and clear the error message, and two actions to commit the mutations.

Step 2: Register the Error Module in Vuex Store

Next, we need to register the error module in the Vuex store. We can do this by importing the error module and adding it to the modules object in the store as shown below:

import Vue from 'vue'
import Vuex from 'vuex'
import error from './error'

Vue.use(Vuex)

export default new Vuex.Store({
  modules: {
    error
  }
})

Step 3: Handle Errors in Axios

Now, we need to handle errors in Axios. We can do this by intercepting the response and dispatching the setError action with the error message as shown below:

import axios from 'axios'
import store from './store'

axios.interceptors.response.use(
  response => response,
  error => {
    const message = error.response.data.message || error.message
    store.dispatch('setError', message)
    return Promise.reject(error)
  }
)

In the above code, we have used Axios interceptors to intercept the response and handle errors. We have dispatched the setError action with the error message and returned a rejected promise.

Step 4: Display Error Messages in Vue Components

Finally, we need to display error messages in Vue components. We can do this by mapping the error state to a computed property and displaying it in the template as shown below:

<template>
  <div v-if="error">{{ error }}</div>
</template>

<script>
import { mapState } from 'vuex'

export default {
  computed: {
    ...mapState(['error'])
  }
}
</script>

In the above code, we have used the mapState helper function to map the error state to a computed property. We have also used a v-if directive to conditionally render the error message.

Method 2: Use Axios Interceptors for Global Error Handling

One of the best practices for error handling in Vue.js is to use Axios interceptors for global error handling. This approach allows you to intercept all HTTP requests and responses, and handle errors in a centralized location.

Here’s how you can implement this approach in your Vue.js application:

Step 1: Install Axios and Vuex

First, you need to install Axios and Vuex using the following command:

npm install axios vuex --save

Step 2: Create a Vuex Module for Error Handling

Next, you need to create a Vuex module for error handling. This module will store the error state and mutations for updating the state.

// src/store/modules/error.js

const state = {
  error: null
}

const mutations = {
  setError (state, error) {
    state.error = error
  },
  clearError (state) {
    state.error = null
  }
}

export default {
  state,
  mutations
}

Step 3: Create an Axios Interceptor for Error Handling

Now, you can create an Axios interceptor for error handling. This interceptor will intercept all HTTP requests and responses, and handle errors in a centralized location.

// src/plugins/axios.js

import axios from 'axios'
import store from '@/store'

// Add a request interceptor
axios.interceptors.request.use(function (config) {
  // Do something before request is sent
  store.commit('clearError')
  return config
}, function (error) {
  // Do something with request error
  return Promise.reject(error)
})

// Add a response interceptor
axios.interceptors.response.use(function (response) {
  // Do something with response data
  return response
}, function (error) {
  // Do something with response error
  if (error.response) {
    store.commit('setError', error.response.data)
  } else {
    store.commit('setError', error.message)
  }
  return Promise.reject(error)
})

Step 4: Import Axios and Vuex into Your Vue.js Application

Finally, you need to import Axios and Vuex into your Vue.js application and use them in your components.

// src/main.js

import Vue from 'vue'
import App from './App.vue'
import axios from 'axios'
import store from './store'

Vue.config.productionTip = false

// Set up Axios
Vue.prototype.$http = axios

// Set up Vuex
Vue.prototype.$store = store

new Vue({
  render: h => h(App),
}).$mount('#app')

Method 3: Handle Errors on a Per-Request Basis with Try-Catch

One of the best practices for error handling in Vue.js with Vuex and Axios is to handle errors on a per-request basis with Try-Catch. This approach allows you to handle errors for specific requests and provide a more meaningful error message to the user.

Here’s an example code snippet that demonstrates how to handle errors on a per-request basis with Try-Catch:

async function fetchData() {
  try {
    const response = await axios.get('/api/data');
    return response.data;
  } catch (error) {
    console.error(error);
    throw new Error('Failed to fetch data from the server.');
  }
}

In this example, we use the axios library to make a GET request to a data API. If the request is successful, we return the data from the response. If an error occurs, we log the error to the console and throw a new error with a custom message.

You can then use this function in your Vue.js component like this:

export default {
  data() {
    return {
      data: null,
      error: null,
    };
  },
  async created() {
    try {
      this.data = await fetchData();
    } catch (error) {
      this.error = error.message;
    }
  },
};

In this example, we define a data object with data and error properties. In the created lifecycle hook, we call the fetchData function and assign the returned data to the data property. If an error occurs, we assign the error message to the error property.

By handling errors on a per-request basis with Try-Catch, you can provide a more meaningful error message to the user and improve the user experience of your Vue.js application.

Method 4: Displaying Error Messages in the UI

When working with Vue.js, Vuex and Axios, it’s important to have a solid error handling strategy in place. One approach is to display error messages directly in the UI. Here’s how you can do it:

Step 1: Create a Vuex module for handling errors

Create a new Vuex module called error that will handle all errors in your application. This module will have a state property called message that will hold the error message.

const state = {
  message: null
};

const mutations = {
  SET_ERROR_MESSAGE(state, message) {
    state.message = message;
  },
  CLEAR_ERROR_MESSAGE(state) {
    state.message = null;
  }
};

const actions = {
  setError({ commit }, message) {
    commit("SET_ERROR_MESSAGE", message);
  },
  clearError({ commit }) {
    commit("CLEAR_ERROR_MESSAGE");
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};

Step 2: Handle errors in Axios requests

In your Axios requests, use a try-catch block to catch any errors that may occur. If an error occurs, dispatch the setError action from the error module.

import axios from "axios";
import store from "@/store";

const apiClient = axios.create({
  baseURL: "https://api.example.com"
});

apiClient.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    if (error.response) {
      store.dispatch("error/setError", error.response.data.message);
    } else {
      store.dispatch("error/setError", "An error occurred. Please try again later.");
    }
    return Promise.reject(error);
  }
);

export default {
  getSomeData() {
    return apiClient.get("/data");
  }
};

Step 3: Display error messages in the UI

In your Vue components, use a computed property to get the error message from the error module. If the error message exists, display it in the UI.

<template>
  <div>
    <p v-if="errorMessage">{{ errorMessage }}</p>
    <button @click="getData">Get Data</button>
  </div>
</template>

<script>
import { mapState, mapActions } from "vuex";
import api from "@/api";

export default {
  computed: {
    ...mapState("error", ["message"]),
    errorMessage() {
      return this.message ? `Error: ${this.message}` : null;
    }
  },
  methods: {
    ...mapActions("error", ["clearError"]),
    async getData() {
      try {
        this.clearError();
        const response = await api.getSomeData();
        // Do something with response
      } catch (error) {
        // Error will be displayed in the UI
      }
    }
  }
};
</script>

That’s it! With this approach, you can easily handle errors in your Vue.js application, display error messages in the UI, and keep your code organized using Vuex.

closeup photo of yellow Labrador retriever puppy

Sometimes, we want to handle errors in Vue.js with Vuex and Axios.

In this article, we’ll look at how to handle errors in Vue.js with Vuex and Axios.

How to handle errors in Vue.js with Vuex and Axios?

To handle errors in Vue.js with Vuex and Axios, we can add a response interceptor.

For instance, we write

axios.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    store.commit("ERROR", error);
    return Promise.reject(error);
  }
);

to call axios.interceptors.response.use with the error handler in the 2nd argument.

In it, we call store.commit to put the error data in the Vuex store by committing the ERROR mutation.

And then we return a rejected promise with the error as the rejection reason.

Then we can catch any request errors with a catch block:

try {
  await axios.get("...");
} catch (e) {
  console.log(e);
}

Conclusion

To handle errors in Vue.js with Vuex and Axios, we can add a response interceptor.

Web developer specializing in React, Vue, and front end development.

View Archive

Answer by Teresa Adams

API error handling in vue with axios
,Tags: axios, error handling, interceptor,Since all the app needs this error handling let’s put it in a module so you can reuse it in any vuejs app or any app in general which uses axios to make HTTP calls.,For simplicity, I am keeping only error and success type notification, but you can add all the features your app needed for notification.

Since axios is promise based HTTP library we can handle any error using then(response) and catch(error), but if you are not careful you will end up scattering catch() block throughout your application. In most cases, you will be showing some type of alert message to the screen.

axios.get('/user/1').then((response) => {
    console.log('Everything is awesome.');
}).catch((error) => {
    console.warn('Not good man :(');
})

Add following in resources/assets/js/bootstrap.js after axios import.

axios.interceptors.response.use(
function(response) { return response;}, 
function(error) {
    // handle error
    if (error.response) {
        alert(error.response.data.message);
    }
});

Now pull the iziToast using npm and create a resources/assets/js/services/toast.js and add following code.

import 'izitoast/dist/css/iziToast.min.css'
import iZtoast from 'izitoast'

const toast = {
    error: (message, title = 'Error') => {
        return iZtoast.error({
            title: title,
            message: message,
            position: 'bottomCenter'
        });
    },
    success: (message, title = 'Success') => {
        return iZtoast.success({
            title: title,
            message: message,
            position: 'bottomCenter'
        });
    }
};

export default toast;

Now let’s update the interceptor to use our toast notification instead boring alert box.

import toast from './toast'

axios.interceptors.response.use(
...
function(error) {
    // handle error
    if (error.response) {
        toast.error(error.response.data.message);
    }
});

I came across many scenarios where a global error handler was not a good choice. For example, if there is a request which error format is different or unique like currently, we are expecting message key in error response which is default in Laravel for any error. But if you are making calls to different API provider or you want to customize the notification, what to do then? Don’t worry axios configuration can help with this.

axios.get('/user/1', {errorHandle: false}).then((response) => {
    console.log('Everything is awesome.');
}).catch((error) => {
    // handle this error here
    alert('Not good man :(');
})

By passing a config property {errorHandle: false} in axios request we can turn off the error handling for this call. Now let’s modify the interceptor to make it happen.

axios.interceptors.response.use(
function (response) {
    return response;
}, 
function(error) {
    // check for errorHandle config
    if( error.config.hasOwnProperty('errorHandle') && error.config.errorHandle === false ) {
        return Promise.reject(error);
    }

    if (error.response) {
        toast.error(error.response.data.message);
    }
});

Create resources/assets/js/services/errorHandler.js and add following code

import axios from 'axios'
import toast from './toast'

function errorResponseHandler(error) {
    // check for errorHandle config
    if( error.config.hasOwnProperty('errorHandle') && error.config.errorHandle === false ) {
        return Promise.reject(error);
    }

    // if has response show the error 
    if (error.response) {
        toast.error(error.response.data.message);
    }
}

// apply interceptor on response
axios.interceptors.response.use(
   response => response,
   errorResponseHandler
);

export default errorResponseHandler;

This module is applying the response interceptor to handle the errors during a request. To use it just import it in your resources/assets/js/bootstrap.js like this.

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

require('./services/errorHandler');

Answer by Jeremy Meyer

What about direct import your store to ApiClient.js? Something like,Now you can import { $store } from ‘@/main.js’ anywhere you want. And it’s going to be the same instance you have mounted in your app, not a new Vuex.Store({}) (which is what ./store exports, each time you import it somewhere else). ,

Companies

,The Axios file contains an export default class API that is added to Vue globally in main.js:

main.js:

import store from './store';

const Instance = new Vue({
  store,
  ...
})

export const { $store } = Instance;

You can export the same way anything else you might want to use in services, tests, helpers, etc… I.e:

export const { $store, $http, $bus, $t } = Instance;

Answer by Nikolas Lester

axios.get('/user/1').then((response) => {
    console.log('Everything is awesome.');
}).catch((error) => {
    console.warn('Not good man :(');
})

Answer by Hudson Person

Excellent! We’ve got some data. But it looks pretty messy right now so let’s display it properly and add some error handling in case things aren’t working as expected or it takes longer than we thought to get the information.,You can hit the rerun button on this pen to see the loading status briefly while we gather data from the API:,There are times when we might not get the data we need from the API. There are several reasons that our axios call might fail, including but not limited to:,It’s pretty typical that the information we’ll need is within the response, and we’ll have to traverse what we’ve just stored to access it properly. In our case, we can see that the price information we need lives in response.data.bpi. If we use this instead, our output is as follows:

There are a number of ways we can request information from the API, but it’s nice to first find out what the shape of the data looks like, in order to know what to display. In order to do so, we’ll make a call to the API endpoint and output it so we can see it. We can see in the CoinDesk API documentation, that this call will be made to https://api.coindesk.com/v1/bpi/currentprice.json. So first, we’ll create a data property that will eventually house our information, and we’ll retrieve the data and assign it using the mounted lifecycle hook:

new Vue({
  el: '#app',
  data () {
    return {
      info: null
    }
  },
  mounted () {
    axios
      .get('https://api.coindesk.com/v1/bpi/currentprice.json')
      .then(response => (this.info = response))
  }
})
new Vue({
  el: '#app',
  data () {
    return {
      info: null
    }
  },
  mounted () {
    axios
      .get('https://api.coindesk.com/v1/bpi/currentprice.json')
      .then(response => (this.info = response))
  }
})
<div id="app">
  {{ info }}
</div>

It’s pretty typical that the information we’ll need is within the response, and we’ll have to traverse what we’ve just stored to access it properly. In our case, we can see that the price information we need lives in response.data.bpi. If we use this instead, our output is as follows:

axios
  .get('https://api.coindesk.com/v1/bpi/currentprice.json')
  .then(response => (this.info = response.data.bpi))

This is a lot easier for us to display, so we can now update our HTML to display only the information we need from the data we’ve received, and we’ll create a filter to make sure that the decimal is in the appropriate place as well.

<div id="app">
  <h1>Bitcoin Price Index</h1>
  <div
    v-for="currency in info"
    class="currency"
  >
    {{ currency.description }}:
    <span class="lighten">
      <span v-html="currency.symbol"></span>{{ currency.rate_float | currencydecimal }}
    </span>
  </div>
</div>
<div id="app">
  <h1>Bitcoin Price Index</h1>
  <div
    v-for="currency in info"
    class="currency"
  >
    {{ currency.description }}:
    <span class="lighten">
      <span v-html="currency.symbol"></span>{{ currency.rate_float | currencydecimal }}
    </span>
  </div>
</div>
filters: {
  currencydecimal (value) {
    return value.toFixed(2)
  }
},

When making this request, we should be checking for just such circumstances, and giving ourselves information in every case so we know how to handle the problem. In an axios call, we’ll do so by using catch.

axios
  .get('https://api.coindesk.com/v1/bpi/currentprice.json')
  .then(response => (this.info = response.data.bpi))
  .catch(error => console.log(error))

This will let us know if something failed during the API request, but what if the data is mangled or the API is down? Right now the user will just see nothing. We might want to build a loader for this case, and then tell the user if we’re not able to get the data at all.

new Vue({
  el: '#app',
  data () {
    return {
      info: null,
      loading: true,
      errored: false
    }
  },
  filters: {
    currencydecimal (value) {
      return value.toFixed(2)
    }
  },
  mounted () {
    axios
      .get('https://api.coindesk.com/v1/bpi/currentprice.json')
      .then(response => {
        this.info = response.data.bpi
      })
      .catch(error => {
        console.log(error)
        this.errored = true
      })
      .finally(() => this.loading = false)
  }
})
new Vue({
  el: '#app',
  data () {
    return {
      info: null,
      loading: true,
      errored: false
    }
  },
  filters: {
    currencydecimal (value) {
      return value.toFixed(2)
    }
  },
  mounted () {
    axios
      .get('https://api.coindesk.com/v1/bpi/currentprice.json')
      .then(response => {
        this.info = response.data.bpi
      })
      .catch(error => {
        console.log(error)
        this.errored = true
      })
      .finally(() => this.loading = false)
  }
})
<div id="app">
  <h1>Bitcoin Price Index</h1>

  <section v-if="errored">
    <p>We're sorry, we're not able to retrieve this information at the moment, please try back later</p>
  </section>

  <section v-else>
    <div v-if="loading">Loading...</div>

    <div
      v-else
      v-for="currency in info"
      class="currency"
    >
      {{ currency.description }}:
      <span class="lighten">
        <span v-html="currency.symbol"></span>{{ currency.rate_float | currencydecimal }}
      </span>
    </div>

  </section>
</div>

Answer by Lainey Peterson

new Vue({  el: '#app',  data () {    return {      info: null    }  },  mounted () {    axios      .get('https://api.coindesk.com/v1/bpi/currentprice.json')      .then(response => (this.info = response))  }})

Answer by Azariah Griffith

new Vue({  el: '#app',  data () {    return {      info: null    }  },  mounted () {    axios      .get('https://api.coindesk.com/v1/bpi/currentprice.json')      .then(response => (this.info = response))  }})

Answer by Eduardo Norman

In many scenarios where a global error handler was not a good choice,axios configuration can help with this.,Adding a response Interceptor,Now it’s time to add Axios Interceptor:,And Just plain alert() box is not a great way to show errors, you cannot customize them and they look very ugly. So I got this VueSwal library with lots of configuration.

Create a new instance and add any global config options you might need to use using Axios.

const axiosInstance = axios.create({  baseURL: 'https://aq7qbiaz..'});

To configure it in Vue, below snippet need to write in main.js in Vue app,

import Vue from 'vue'import Loading from 'vue-loading-overlay';import 'vue-loading-overlay/dist/vue-loading.css';import VueSwal from 'vue-swal';import App from './App.vue';Vue.use(Loading);Vue.use(VueSwal);new Vue({router,render: h => h(App),}).$mount('#app')

I will add a loader and attach Authorization token in the “AUTHORIZER HTTP header with each axios HTTP request . Here Request interceptors is used to do things such as retrieve a token from local storage and send with all requests,

import axios from "axios";// Add a request interceptorlet loader;axios.interceptors.request.use(      config => {       //Showing Vue loader before every request                loader = this.$loading.show({            // Optional parameters            container: this.fullPage ? null : this.$refs.formContainer,            canCancel: false,            onCancel: this.onCancel          });        }        const token = localStorage.getItem("token");        if (token) {          config.headers.common["AUTHORIZER"] = token; /set Auth token        }        return config;      },      (error) => {        return Promise.reject(error);      });

In many scenarios where a global error handler was not a good choice,axios configuration can help with this.

// Add a response interceptoraxios.get('http://xyz', {errorHandle: false}).then((response) => {    console.log('Success :)');}).catch((error) => {    // handle and customize this error here    alert('Error :(;})

Here response interceptor is used to catch all responses. We have two callbacks in response interceptors. One gets executed when we have a response from the HTTP call and another gets executed when we have an error and redirect to a login page for authorization when get 401 status in error callback.

// Add a response interceptoraxios.interceptors.response.use((response) => {    // Do something with response data    loader.hide(); //hiding loader on when receive response    return response;  }, (error) => {     // check for errorHandle config     if (error.config.hasOwnProperty("errorHandle") &&              error.config.errorHandle === false) {        loader.hide(); //hiding loader on error        return Promise.reject(error);     }     // Do something with response error     if (error.response.status) {              loader.hide(); //hiding loader on error//Handling different error status using Switch caase                           switch (error.response.status) {                case 400:                  this.$swal(error.response.data.message, {                    closeOnClickOutside: false                  }); //showing Swal Alert                  break;                case 401:                  //logout user                  this.$swal(error.response.data.message, {                    closeOnClickOutside: false                  }); //showing Swal Alert                  break;                case 403:                  this.$swal(error.response.data.message, {                    closeOnClickOutside: false                  }); //showing Swal Alert                  break;                case 404:                  this.$swal(error.response.data.message, {                    closeOnClickOutside: false                  }); //showing Swal Alert                  break;                case 500:                  this.$swal(error.response.data.message, {                    closeOnClickOutside: false                  }); //showing Swal Alert              }            }          }  });

Answer by Dustin McPherson

Vue + Fetch — HTTP GET Request Examples
,This sends the same GET request again from Vue using axios with the HTTP Content-Type header set to application/json.,Below is a quick set of examples to show how to send HTTP GET requests from Vue to a backend API using the axios HTTP client which is available on npm.,
Vue + Axios — HTTP POST Request Examples

This sends an HTTP GET request from Vue to the npm api to search for all vue packages using the query q=vue, then assigns the total returned in the response to the component data property totalVuePackages so it can be displayed in the component template.

created() {
  // Simple GET request using axios
  axios.get("https://api.npms.io/v2/search?q=vue")
    .then(response => this.totalVuePackages = response.data.total);
}

This sends the same GET request from Vue using axios, but this version uses an async function and the await javascript expression to wait for the promises to return (instead of using the promise then() method as above).

async created() {
  // GET request using axios with async/await
  const response = await axios.get("https://api.npms.io/v2/search?q=vue");
  this.totalVuePackages = response.data.total;
}

This sends a GET request from Vue to an invalid url on the npm api then assigns the error message to the errorMessage component data property and logs the error to the console.

created() {
  // GET request using axios with error handling
  axios.get("https://api.npms.io/v2/invalid-url")
    .then(response => this.totalVuePackages = response.data.total)
    .catch(error => {
      this.errorMessage = error.message;
      console.error("There was an error!", error);
    });
}

This sends the same GET request again from Vue using axios with the HTTP Content-Type header set to application/json.

created() {
  // GET request using axios with set headers
  const headers = { "Content-Type": "application/json" };
  axios.get("https://api.npms.io/v2/search?q=vue", { headers })
    .then(response => this.totalVuePackages = response.data.total);
}

Answer by Alberto Curtis

Im trying to catch validation errors from the server.,Vue-template-compiler 2.3.4,Modify from console.log(error) to console.log(error.response) in catch.,I should be seeing an object that contains JSON form validation as that is the response in my network tab, i seem to get the JS catch output?

axios.post('/formulas/create', {
       name: "",
       parts: ""
})
.then( 
	(response) => { console.log(response) },
	(error) => { console.log(error) }
);

Answer by Zoya Kirby

You can turn off the global error handling for a specific request by passing {errorHandle: false} as config in axios call.,Typo in «Turn on gloabl error handling for specific call»,This doesn’t seem to work with axios 0.19.x. Any idea how to pass the errorHandle flag in the latest version of axios?,I am assuming you have a Laravel app with axios installed.

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

require('./services/errorHandler');

Answer by Jaylen Crawford

Using the ErrorService class in Vuex is a great way to handle and process HTTP errors from Axios. You can also store the errors in Vuex State so they can be displayed to the user gracefully.,The ErrorService class will handle all your errors and decide how to process them.,In any application I develop, I always formulate a plan for handling errors, usually by creating a generic ErrorService class and including functions to handle and process the errors coming in according to their type.,Vue.js offers an error handler to catch all possible Vue errors. You can do this inside the main.js file.

The ErrorService class will handle all your errors and decide how to process them.

import Swal from "sweetalert2";
import "sweetalert2/dist/sweetalert2.min.css";

export default class ErrorService {
  constructor() {
    // this.initHandler();
  }

  static onError(error) {
    const response = error.response;
    if (response && response.status >= 400 && response.status < 405) {
      // You can handle this differently
      ErrorService.sentryLogEngine(error);
      return false;
    }
    // Send Error to Log Engine e.g LogRocket
    ErrorService.logRocketLogEngine(error);
  }

  static onWarn(error) {
    // Send Error to Log Engine e.g LogRocket
    this.logRocketLogEngine(error);
  }

  static onInfo(error) {
    // You can handle this differently
    this.sentryLogEngine(error);
  }

  static onDebug(error) {
    const response = error.response;
    if (response && response.status >= 400 && response.status < 405) {
      // You can handle this differently
      this.sentryLogEngine(error);
      return false;
    }
    // Send Error to Log Engine e.g LogRocket
    this.logRocketLogEngine(error);
  }

  static initHandler() {
    const scope = this;
    window.onerror = (message, url, lineNo, columnNo, error) => {
      console.log(error, "test");
      if (error) {
        scope.onError(error);
        console.log(message, url, lineNo, columnNo, error);
      }
    };
  }

  static displayErrorAlert(message) {
    Swal.fire({
      title: "Error!",
      text: message,
      icon: "error",
    });
  }

  static logRocketLogEngine(error) {
    // Implement LogRocket Engine here
    console.log(error, "LogRocket");
  }

  static sentryLogEngine(error) {
    // Implement Sentry Engine here
    console.log(error, "Sentry");
  }
}

Vue.js offers an error handler to catch all possible Vue errors. You can do this inside the main.js file.

import Vue from "vue";
import App from "./App.vue";
import { ErrorService } from "./Services/ErrorService";
import store from "./store";

Vue.config.productionTip = false;

// Handle all Vue errors
Vue.config.errorHandler = (error) => ErrorService.onError(error);

new Vue({
  store,
  render: (h) => h(App),
}).$mount("#app");

Using the ErrorService class in Vuex is a great way to handle and process HTTP errors from Axios. You can also store the errors in Vuex State so they can be displayed to the user gracefully.

import Vue from "vue";
import Vuex from "vuex";
import { ErrorService } from "./Services/ErrorService";
import axios from "axios";

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    todos: [],
    errors: [],
    users: [],
  },

  actions: {
    async getTodos({ commit }) {
      try {
        const response = await axios.get(
          `https://jsonplaceholder.typicode.com/todos`
        );
        const { data } = response;
        commit("STORE_TODOS", data);
      } catch (error) {
        // Handling HTTPs Errors
        commit("STORE_ERRORS", error);
      }
    },

    async getUsers({ commit }) {
      try {
        const response = await axios.get(
          `https://jsonplaceholder.typicode.com/users`
        );
        const { data } = response;
        commit("STORE_USERS", data);
      } catch (error) {
        // Handling HTTPs Errors
        commit("STORE_ERRORS", error);
      }
    },
  },

  mutations: {
    STORE_TODOS: (state, data) => {
      state.todos = data;
    },

    STORE_ERRORS: (state, error) => {
      // Call Error Service here
      ErrorService.onError(error);
      ErrorService.initHandler();

      // Store error to state(optional)
      if (error.response) {
        state.errors = error.response;
      }
    },

    STORE_USERS: (state, data) => {
      state.users = data;
    },
  },

  getters: {
    getTodo: (state) => (id) => {
      return state.todos.find((todo) => todo.id == id);
    },
    getUser: (state) => (id) => {
      return state.users.find((user) => user.id == id);
    },
  },

  // strict: true
});

export default store;

Since the errors are saved in the Vuex State, which enables us to leverage the reactivity of Vue, we can display them on the error component like so:

<script>
import { mapGetters } from "vuex";
import ErrorService from "../Services/ErrorService";

export default {
  name: "HelloWorld",
  props: {
    todo: Object,
  },
  computed: {
    ...mapGetters(["getUser"]),
  },

  methods: {
    getUserName(id) {
      const user = this.getUser(id);
      if (user) return user.username;
    },

    // Handling Errors in component
    methodThrowsException() {
      try {
        // Do unexpected job
      } catch (error) {
        ErrorService.onError(error);
      }
    },
  },
};
</script>

You can display these errors to the user in different ways. We’ll use the vue-sweetalert2 plugin to display our errors.

<script>
import { mapGetters } from "vuex";
import ErrorService from "../Services/ErrorService";

export default {
  name: "HelloWorld",
  props: {
    todo: Object,
  },
  computed: {
    ...mapGetters(["getUser"]),
  },

  methods: {
    getUserName(id) {
      const user = this.getUser(id);
      if (user) return user.username;
    },

    // Display Error with SweetAlert (when Name is Click)
    displayAlert() {
      ErrorService.displayErrorAlert("Testing message");
    },
  },
};
</script>

Answer by Addilynn Moon

Axios requests are promises, which means they have a then() function for promise chaining, and
a catch() function for handling errors. Below is how you can catch()
an error in Axios.,Axios’ catch() behaves exactly the same as the promise catch() function. So you can use promise chaining, and add a catch() at the
end to handle any errors that occur in the promise chain.,You can also make Axios transform errors automatically using interceptors.,You can also use catch() to transform the error, just make sure you
rethrow the error afterwards.

Axios requests are promises, which means they have a then() function for promise chaining, and
a catch() function for handling errors. Below is how you can catch()
an error in Axios.

const err = await axios.get('https://httpbin.org/status/404').
  catch(err => err);

err instanceof Error; // true
err.message; // 'Request failed with status code 404'

Axios’ catch() behaves exactly the same as the promise catch() function. So you can use promise chaining, and add a catch() at the
end to handle any errors that occur in the promise chain.

const err = await axios.get('https://httpbin.org/status/200').
  // Will throw a TypeError because the property doesn't exist.
  then(res => res.doesNotExist.throwAnError).
  catch(err => err);

err instanceof TypeError; // true

You can also use catch() to transform the error, just make sure you
rethrow the error afterwards.

let error;
try {
  await axios.get('https://httpbin.org/status/404').catch(err => {
    if (err.response.status === 404) {
      throw new Error(`${err.config.url} not found`);
    }
    throw err;
  });
} catch (err) {
  error = err;
}

error.message; // "https://httpbin.org/status/404 not found"

I am planing to execute all server CRUDing transmissions via vuex by axios. like:

actions: { // dispatch
    createCategory(ctx) {
        return axios.post(process.env.API_URL + "category/create/", category)
            .then(response => {
                ctx.commit('UPDATE_CATEGORY', response.data.updated_category);
                return response;
            }).catch(error => {
                return error;
            })
...

and then call them within component like

this.$store.dispatch("createCategory", category)
    .then(response => { DO NOTIFICATION STUFF }  
    .catch(error => { this.errors = error }

(I probably will need a promise and reject() within the axios for catching error but that’s not the point)

My question is should I handle the error this way (component) locally or should I handle it globally with a vuex state like

actions: { // dispatch
    createCategory(ctx) {
        return axios.post(process.env.API_URL + "category/create/", category)
            .then(response => {
                ctx.commit('UPDATE_CATEGORY', response.data.updated_category);
                return response;
            }).catch(error => {
                ctx.commit('SET_ERROR', error)
            })
...

and call the errors within the component like: this.$store.getters['getErrors'] ?

(the examples here are kinda abstract just for explanation purpose)

So which way is better practice handle error locally within component or globally within vuex store?

Понравилась статья? Поделить с друзьями:
  • Axion ошибка rtc
  • Axioma кондиционеры коды ошибок
  • Autodata ошибка e0209 sentinel key not found
  • Autocad фатальная ошибка штриховка
  • Automation ошибка при запуске