JAVASCRIPT

Vue 3 Global Error Handling with onErrorCaptured

Catch and handle errors from child components or their lifecycle hooks in Vue 3 using the `onErrorCaptured` hook, creating robust error boundaries.

// ErrorBoundary.vue (Parent Component)
<template>
  <div class="error-boundary">
    <div v-if="error">{{ error }}</div>
    <div v-else>
      <p>This component acts as an error boundary.</p>
      <slot></slot>
    </div>
  </div>
</template>

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

const error = ref(null);

// This hook captures errors from any descendant components
onErrorCaptured((err, instance, info) => {
  error.value = `Caught error: ${err.message} in ${instance?.type.__name || 'unknown component'} during ${info}`;
  console.error("Error captured by boundary:", err, instance, info);
  // Return false to stop the error from propagating further up the component tree
  // or to global error handlers.
  return false;
});
</script>

<style scoped>
.error-boundary {
  border: 2px solid #ff0000;
  padding: 15px;
  margin: 15px 0;
  background-color: #ffebeb;
  color: #c00;
  font-weight: bold;
}
</style>

// MalfunctioningChild.vue
<template>
  <div>
    <h4>Malfunctioning Child Component</h4>
    <button @click="throwError">Click to cause error</button>
  </div>
</template>

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

const throwError = () => {
  throw new Error('Something went wrong in MalfunctioningChild!');
};

// Example of an error during a lifecycle hook
onMounted(() => {
  // Uncomment the line below to see an error during mounting
  // throw new Error('Error during child component mount!');
});
</script>

// App.vue
<template>
  <div>
    <h1>App Root</h1>
    <ErrorBoundary>
      <MalfunctioningChild />
    </ErrorBoundary>
    <p>This content is outside the error boundary and will render normally.</p>
  </div>
</template>

<script setup>
import ErrorBoundary from './ErrorBoundary.vue';
import MalfunctioningChild from './MalfunctioningChild.vue';
</script>
How it works: This snippet demonstrates `onErrorCaptured` in Vue 3, allowing a parent component to act as an error boundary. When an error occurs in any of its descendant components (e.g., `MalfunctioningChild`), `onErrorCaptured` intercepts it, preventing the entire application from crashing. The error can then be displayed gracefully, and optionally, further propagation can be stopped by returning `false`.

Need help integrating this into your project?

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

Hire DigitalCodeLabs