Having difficulty running vue's global errorHandler in certain situations

Encountering issues with a vue 2 project where the global error handler defined in main.js is not functioning, similar to a demo facing the same issue

Vue 3 https://stackblitz.com/edit/vitejs-vite-svaosh?file=src%2Fmain.js

Error Handler

app.config.errorHandler = (err) => {
  console.log('error caught');
};

App.vue

<script>
export default {
  created() {
    console.log('jello');
    throw new Error('dasf');
    this.loadData();
  },

  methods: {
    async loadData() {
      throw new Error('dasf');
    },
  },
};
</script>

Both errors are expected to be caught by errorHandler and simply displayed on the console

The assumption is that the errors are within the Vue context rather than the window context, as Vue does not display them as unhandled errors like this

https://i.sstatic.net/DdAlWws4.png

Vue2

Attempting to implement an optional error capturing mechanism where errors thrown by APIs can be caught either in the component or by the global error handler to display a warning toast

Previously working fine, but currently not functioning as intended. The global error handler catches an error thrown in 'created' but not one thrown in 'loadData'

export default {
  async created() {
    this.loadMastersCount();
    throw new Error("dasf"); // this one is caught by global error handler
  },
  methods: {
    async loadMastersCount() {
      throw new Error("dasf"); // this one is not caught and shown in red during development or on screen
    },
  }
}

Edit I managed to get the Vue 2 reproduction working, here it is

Stackblitz

Github

Case 1 - Error thrown in 'loadData' is not caught

<script>
import HelloWorld from './components/HelloWorld.vue'

import { failingApi } from "@/api/dummy";

export default {
  name: 'App',
  components: {
    HelloWorld
  },
  async created() {
    // await failingApi();
    this.loadData();
  },
  methods: {
    async loadData() {
      await failingApi();
    }
  }
}
</script>

https://i.sstatic.net/HLXWbsOy.png


Case 2 - Error thrown in 'created' is caught by global errorHandler

<script>
import HelloWorld from './components/HelloWorld.vue'

import { failingApi } from "@/api/dummy";

export default {
  name: 'App',
  components: {
    HelloWorld
  },
  async created() {
    await failingApi();
    // this.loadData();
  },
  methods: {
    async loadData() {
      await failingApi();
    }
  }
}
</script>

https://i.sstatic.net/2fSdcJSM.png

Please check @moritz-ringler

Answer №1

In the stackblitz, an error is thrown in the created hook before the handler is registered:

const app = createApp(App)
app.mount('#app') // <--- exception is triggered here
app.config.errorHandler = (err) => {...}

To resolve this issue, make sure to register the handler before calling app.mount():

const app = createApp(App)
app.config.errorHandler = (err) => {...}
app.mount('#app')

In the Vue 2 code snippet, it seems like the error occurring in created() isn't caught or thrown because the execution stops after encountering an uncaught error in loadMastersCount().

Remember that you need to await an async function in order to catch errors. Check out this or this answer for a detailed explanation.

Vue.config.errorHandler = (error) => console.log('got global error', error.toString())

const ThrowError = {
  template: `<div>Template</div>`,
  async created() {
    await this.loadData()
  },
  methods: {
    async loadData() {
      await this.throwError()
    },
    async throwError(){
      throw new Error('Error in Promise')
    },
  }
}

new Vue({
  el: '#app',
  components: {ThrowError},
  template: `<ThrowError/>`,
})
<div id="app"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.7.16/vue.min.js"></script>

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

I am interested in having a bilingual link on the main page that directs users to the corresponding page in Spanish or English, rather than back to the homepage

I am currently working on a Visual Studio C# .NET project that has both English and Spanish versions. Each version has its own master template with a link to switch between languages. However, clicking on the language link takes me to the homepage of the c ...

Unable to automatically close browser window after test execution with NightwatchJS

I recently executed my first Nightwatch test, as indicated in the code below. The test ran smoothly - Selenium successfully entered 'wiki' into Google and submitted the form, resulting in a passing test. However, I am now looking to automate the ...

Interactive grid feature created with HTML Canvas

Imagine my surprise when I discovered that the latest version of Google Spreadsheets is now using a canvas tag to render the spreadsheet grid, unlike the traditional <table><tr><td> method used in the past. In the previous version, only ...

Tips for preventing timeouts when posting data to Heroku servers

I have a Ruby on Rails application deployed on Heroku. The app includes 8 optional text fields that users can choose to fill or leave empty as needed. However, the more text fields a user fills out, the heavier the processing load on my app. If there are ...

Retrieving Files using Ajax Across Different File Types

I recently came across the following code snippet: DOM_imgDir = "img/UI/DOM/"; fileextension = ".jpg"; $.ajax({ url: DOM_imgDir, success: function (data) { $(data).find("a:contains(" + fileextension + ")").each(function () { filename = thi ...

Steps to altering the color of a second button with a button click

My goal is to create a button click function that allows only one button to be clicked at a time. For instance, when btn1 is clicked, its background color changes from transparent to green. Then, if btn2 is clicked, btn1's background color should chan ...

Running the command "npm run dev" generates a series of files named 0.js, 1.js, all the way up to 14.js within the

As a novice in the realm of Webpack, NPM, and VueJS, I find myself facing a perplexing issue. Despite my efforts to seek answers online, I remain stumped by the outcome when executing the command npm run dev in VueJS - wherein webpack generates 15 files l ...

Navigation Links in Bootstrap Navbar Deactivated During Ease-In Animation

I am facing an issue with a top sticky navbar on a Bootstrap 4 page. The navbar is set to ease-in/reveal after scrolling down the page, but when it appears, none of the links work, not even changing link colors with :hover. I tried using media queries to h ...

What is the best way to implement function chaining in TypeScript?

I'm interested in implementing function chaining in typescript. Let's consider a sample class: export class NumberOperator { private num; constructor(initialNum) { this.num = initialNum; } public add(inc = 1) { this.num += inc ...

Error encountered while downloading repository vuejs-templates/webpack: certificate in the certificate chain is self-signed

Encountering an error when attempting to execute the vue init webpack command. Error message: "vue-cli · Failed to download repo vuejs-templates/webpack: self signed certificate in certificate chain" What may be causing this issue? I am eager to continu ...

Encountering an unexpected or invalid token in line 1 after reinstallation of Windows can be a frustrating experience

Yesterday, my JavaScript file was running smoothly. However, after reinstalling Windows and Node, I'm encountering an error when trying to run the same JavaScript file today. $ node index.js C:\Users\<user-name>\Google Drive&bsol ...

A guide on extracting text enclosed by <a> and </a> tags using regular expressions

I have come across the following code: <a align="center" href="http://google.com"><b>Google Link<b></b></a> <a align="center" href="http://yahoo.com"><strong>Yahoo Link</strong></a> Now, I am looking ...

Using React-router-dom's Link component can cause styling inconsistencies with material-ui's AppBar Button

Exploring the use of a material-ui Button with react-router-dom's Link is showcased here: import { Link } from 'react-router-dom' import Button from '@material-ui/core/Button'; <Button component={Link} to="/open-collective"> ...

Displaying and hiding content with a single button

I'm working on a slide-in content feature that appears from the left when clicking on the bars icon. Initially, I set it up with separate buttons for opening and closing the content by moving the page left and right. Now, I'm attempting to achiev ...

Trouble with Rails partial refresh using Ajax feature

On the homepage, I would like to display article information to the user. When the user clicks on the My Articles link, the relevant information should be shown without refreshing the entire page: Here is the code for the ArticlesController: def index ...

Verifying user presence in Vue when making edits

Currently, I'm attempting to validate user existence in Vue using Vuetify inputs when trying to edit a User. The goal is to prevent an error if the username already exists, unless it is the old username of the user being edited without any changes mad ...

Finding the largest number that is less than a specified variable within an array

I have a JavaScript array and a variable, set up like this; var values = [0, 1200, 3260, 9430, 13220], targetValue = 4500; How can I efficiently find the largest value in the array that is less than or equal to the given variable? In the provided ex ...

Navigating through a TextArea component in Bootstrap with React

I've developed a scrolling component that works well for scrolling the entire window using the method below. window.scrollBy(0, speed) However, I now want to focus on scrolling within a specific textarea. I'm uncertain how to achieve this usin ...

Is there a way I can modify the display setting to show 4 slides per view?

var swiper = new Swiper(".new-arrival", { slidesPerView: 4, centeredSlides: false, spaceBetween: 30, autoplay: { delay: 5500, disableOnInteraction: false, }, pagination: { el: ".swiper-pagination", type: &qu ...

Utilizing AngularJS to access the scope from a different function in JavaScript

I am interested in using AngularJS to dynamically change variable values within HTML. I understand that an onclick function can be utilized for this purpose, and here is the example JavaScript code: var app = angular.module('graphApp', []); app. ...