JAVASCRIPT

Global Error Handling with app.config.errorHandler in Vue 3

Implement a centralized error handling mechanism in your Vue 3 application using `app.config.errorHandler` to catch and log all unhandled errors.

// src/main.js
import { createApp } from 'vue';
import App from './App.vue';

const app = createApp(App);

// Global error handler
app.config.errorHandler = (err, instance, info) => {
  console.error('Caught by global error handler:');
  console.error('Error:', err);
  console.error('Vue instance:', instance);
  console.error('Error info:', info);
  // You can send this error to an error reporting service like Sentry or LogRocket
  // For example: Sentry.captureException(err, { extra: { info, component: instance?.$.type.__name } });
};

// Global warning handler (for non-critical Vue warnings)
app.config.warnHandler = (msg, instance, trace) => {
  console.warn('Caught by global warn handler:');
  console.warn('Warning:', msg);
  // console.warn('Vue instance:', instance); // Often null for warnings
  // console.warn('Trace:', trace);
  // Optionally suppress specific warnings or send to a logging service
};

app.mount('#app');

// src/components/ErrorProne.vue
<template>
  <div>
    <h2>Error Prone Component</h2>
    <button @click="throwSyncError">Throw Sync Error</button>
    <button @click="throwAsyncError">Throw Async Error</button>
    <button @click="accessUndefined">Access Undefined Prop</button>
  </div>
</template>

<script setup>
import { onMounted } from 'vue';

const throwSyncError = () => {
  throw new Error('This is a synchronous error!');
};

const throwAsyncError = async () => {
  await new Promise(resolve => setTimeout(resolve, 100));
  throw new Error('This is an asynchronous error!');
};

const accessUndefined = () => {
  // Accessing an undefined property will cause an error during rendering or reactivity
  console.log(props.nonExistent.value);
};

onMounted(() => {
  // Error during lifecycle hook
  // throw new Error('Error in onMounted!');
});
</script>

// src/App.vue
<template>
  <ErrorProne />
</template>

<script setup>
import ErrorProne from './components/ErrorProne.vue';
</script>
How it works: This snippet demonstrates how to implement global error handling in a Vue 3 application using `app.config.errorHandler` in your `main.js` file. This handler catches all unhandled errors originating from component render functions, lifecycle hooks, and event handlers. It receives the `err` object, the Vue `instance` where the error originated, and an `info` string indicating the error source. This setup is crucial for centralizing error logging, reporting errors to external services, and improving the robustness of your application. `app.config.warnHandler` can similarly catch Vue-specific warnings.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs