JAVASCRIPT

Centralized Error Handling in Vue 3 with onErrorCaptured

Implement robust, application-wide error handling in Vue 3 components using the `onErrorCaptured` lifecycle hook, gracefully catching and managing component errors.

// ErrorProneChild.vue
<template>
  <div>
    <button @click="throwError">Throw Error</button>
    <p>This component might throw an error.</p>
  </div>
</template>

<script setup>
function throwError() {
  throw new Error('An intentional error from child component!');
}
</script>

// App.vue (Parent Component demonstrating error handling)
<template>
  <div>
    <h1>App Component</h1>
    <p v-if="error">{{ errorInfo }}</p>
    <ErrorProneChild />
    <AnotherComponent />
  </div>
</template>

<script setup>
import { ref, onErrorCaptured } from 'vue';
import ErrorProneChild from './components/ErrorProneChild.vue'; // Adjust path
import AnotherComponent from './components/AnotherComponent.vue'; // Example sibling (can be empty for this example)

const error = ref(null);
const errorInfo = ref('');

onErrorCaptured((err, instance, info) => {
  error.value = err;
  errorInfo.value = `Caught an error: ${err.message}. Instance: ${instance?.type.__name}. Info: ${info}`;
  console.error('Caught error in onErrorCaptured:', err, instance, info);
  // Prevent error from propagating further up the component tree
  // or to the global error handler if needed.
  return false; // Returning false stops the propagation
});
</script>
How it works: This snippet illustrates how to use Vue 3's `onErrorCaptured` lifecycle hook for centralized error handling within a component tree. When an error is thrown by a child component (or any descendant), `onErrorCaptured` in a parent component will catch it. The hook provides the error, the component instance that caused it, and a string containing error source info. This allows you to log errors, display user-friendly messages, or perform recovery actions. Returning `false` from `onErrorCaptured` prevents the error from propagating further up the component hierarchy or to the global `app.config.errorHandler`.

Need help integrating this into your project?

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

Hire DigitalCodeLabs