14

I have a component where I use lots of axios with then().catch() inside the catch I am always throwing console.error() like:

axios.get(
 //...
).then(
 //...
).catch(
 error => {
  console.error(..)
 }
)

and there are other few places I throw errors too. I'm looking if there is a way to globally handle errors. I know maybe for the axios I can user interceptor but does vue components have away to catch errors, so I can unify them inside one function?

1 Answer 1

18

Vue API provides the errorHandler, but it won't catch errors in methods (emphasis mine):

Assign a handler for uncaught errors during component render function and watchers.

Examples below.

Handling of error during component render:

Vue.config.errorHandler = function (err, vm, info)  {
  console.log('[Global Error Handler]: Error in ' + info + ': ' + err);
};

Vue.component('person', {template: '#person-template', props: ['person']});
new Vue({
  el: '#app',
  data: {
    people: [
      {name: 'Check the console', address: {zip: 4444}},
      {name: 'No address',     /* address: {zip: 5555} */}
    ]
  }
})
<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>
<template id="person-template">
  <div>
    Name: <b>{{ person.name }}</b> - Zip: {{ person.address.zip }}
  </div>
</template>
<div id="app">
  <div v-for="person in people">
    <person :person="person"></person>
  </div>
</div>

Handling of error inside watcher:

Vue.config.errorHandler = function (err, vm, info)  {
  console.log('[Global Error Handler]: Error in ' + info + ': ' + err);
};

Vue.component('person', {template: '#person-template', props: ['person']});
new Vue({
  el: '#app',
  data: {
    message: "Some message"
  },
  watch: {
    message() {
      console.log(this.message.trim());
    }
  }
})
<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>

<div id="app">
  Message: {{ message }}
  <br>
  <button @click="message = null">click here to set message to null and provoke watcher error</button>
</div>

But...

...unfortunately, the errorHandler doesn't work for methods:

Vue.config.errorHandler = function (err, vm, info)  {
  console.log('[Global Error Handler]: Error in ' + info + ': ' + err);
};

Vue.component('person', {template: '#person-template', props: ['person']});
new Vue({
  el: '#app',
  methods: {
    goMethod() {
      console.log(this.invalidProperty.trim());
    }
  }
})
<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>

<div id="app">
  <button @click="goMethod">click to execute goMethod() and provoke error that will NOT be handled by errorHandler</button>
</div>

Finally:

I know maybe for the axios I can user interceptor but does vue components have away to catch errors, so I can unify them inside one function?

Bottom line is there's currently no way to unify them in one function in Vue.

So your guess is right, your best bet is to define axios interceptors:

Axios Interceptors

You can intercept requests or responses before they are handled by then or catch.

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    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
    return Promise.reject(error);
  });
Sign up to request clarification or add additional context in comments.

3 Comments

This should really have had more visibility, it really helped me A LOT thanks! This should be the google result for when you're looking log related searches including Vue, using your suggestion of Vue.config.errorHandler plus vuejs-logger, is the solution I needed for completing vuejs-logger combo. Thanks @acdcjunior ! Btw, that was such a nice answer! Ironic how sometimes oneself answers a line and gets more upvotes than with a really well structured one like this.
"unfortunately, the errorHandler doesn't work for methods" I wonder why this is the case, and why the docs don't mention it. But, as the comment above noted, this is a great answer, I wish I could upvote it twice
@Aurelio Yeah, I also wonder. Good thing there's that demo, when they perhaps improve it in future versions we can verify it right away.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.