← Back to all snippets
JAVASCRIPT

Implementing Component Error Handling with Vue 3 `onErrorCaptured`

Build robust Vue 3 applications by using `onErrorCaptured` to gracefully handle errors within child components, preventing crashes and improving user experience.

// src/components/ErrorProneComponent.vue
<template>
  <div style="border: 1px solid red; padding: 10px; margin-top: 10px;">
    <h3>Error-Prone Component</h3>
    <button @click="throwError">Trigger Error</button>
    <p v-if="errorTriggered">Error was triggered inside this component.</p>
  </div>
</template>

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

const errorTriggered = ref(false);

const throwError = () => {
  errorTriggered.value = true;
  // Simulate an error
  throw new Error('Something went wrong in ErrorProneComponent!');
};
</script>

// src/App.vue
<template>
  <div>
    <h1>Vue 3 Error Handling Demo</h1>
    <p>Click the button in the red box to trigger an error.</p>

    <div v-if="errorMessage" style="border: 2px solid orange; padding: 15px; background-color: #fff3e0; color: #d84315;">
      <strong>Caught Error:</strong> {{ errorMessage }}
      <p>The application did not crash due to `onErrorCaptured`.</p>
      <button @click="clearError">Clear Error</button>
    </div>

    <ErrorProneComponent />
    <ErrorProneComponent /> <!-- Can have multiple error-prone components -->
  </div>
</template>

<script setup>
import { ref, onErrorCaptured } from 'vue';
import ErrorProneComponent from './components/ErrorProneComponent.vue';

const errorMessage = ref('');

// This hook captures errors from any descendant components
onErrorCaptured((err, instance, info) => {
  console.error('Caught an error!', err.message, instance, info);
  errorMessage.value = err.message;
  // Prevent the error from propagating further up the component tree
  return false; // Returning false will stop error propagation
});

const clearError = () => {
  errorMessage.value = '';
};
</script>
How it works: Vue 3's `onErrorCaptured` is a composition API hook that allows a parent component to intercept errors thrown by any of its child components in its subtree. This snippet demonstrates how to use `onErrorCaptured` in `App.vue` to catch errors originating from `ErrorProneComponent`. By returning `false` from the hook, we prevent the error from propagating further up, enabling the application to handle the error gracefully, display a user-friendly message, and prevent a full application crash.

Need help integrating this into your project?

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

Hire DigitalCodeLabs