JAVASCRIPT

Catch Component Errors with Vue 3 onErrorCaptured

Implement robust error boundaries in your Vue 3 applications using `onErrorCaptured` to gracefully handle errors from child components, preventing crashes.

// App.vue
<template>
  <div>
    <h1>App with Error Boundary</h1>
    <ErrorBoundary>
      <MaybeFailingComponent />
    </ErrorBoundary>
    <p>This content is safe from child component errors above.</p>
  </div>
</template>

<script setup>
import ErrorBoundary from './components/ErrorBoundary.vue';
import MaybeFailingComponent from './components/MaybeFailingComponent.vue';
</script>

// components/ErrorBoundary.vue
<template>
  <div v-if="hasError" style="border: 2px dashed red; padding: 15px; background: #ffebeb;">
    <p>Something went wrong in a child component!</p>
    <p>Error details: {{ error }}</p>
    <button @click="resetError">Try Again</button>
  </div>
  <slot v-else></slot>
</template>

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

const hasError = ref(false);
const error = ref(null);

// This lifecycle hook captures errors from any descendant component
onErrorCaptured((err, instance, info) => {
  console.error("Caught error in ErrorBoundary:", err, info);
  hasError.value = true;
  error.value = err.message || 'Unknown error';
  // Return `false` to stop the error from propagating further up the component chain
  // Return `true` (or nothing) to allow it to continue propagating
  return false;
});

const resetError = () => {
  hasError.value = false;
  error.value = null;
};
</script>

// components/MaybeFailingComponent.vue
<template>
  <div style="border: 1px solid gray; padding: 10px; margin: 10px;">
    <h2>A Component that Might Fail</h2>
    <button @click="triggerError">Trigger Error</button>
    <p v-if="successMsg">{{ successMsg }}</p>
  </div>
</template>

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

const successMsg = ref('');

const triggerError = () => {
  // Simulate an error
  if (Math.random() > 0.5) {
    throw new Error('Something went wrong inside MaybeFailingComponent!');
  } else {
    successMsg.value = 'Operation successful!';
  }
};
</script>
How it works: The `onErrorCaptured` lifecycle hook in Vue 3 allows a parent component to capture errors originating from any of its descendant components. This is crucial for creating error boundaries, which prevent an error in one part of your application from crashing the entire UI. When an error is caught, you can display a fallback UI, log the error, and optionally prevent the error from propagating further up the component tree by returning `false` from the handler function.

Need help integrating this into your project?

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

Hire DigitalCodeLabs