JAVASCRIPT

Implementing Localized Error Handling in Vue 3 with `onErrorCaptured`

Learn to catch and handle errors from descendant components using Vue 3's `onErrorCaptured` hook, creating robust and resilient user interfaces by isolating failures.

<!-- ErrorBoundary.vue -->
<template>
  <div class="error-boundary">
    <template v-if="error">
      <p>Something went wrong!</p>
      <p class="error-message">{{ error.message }}</p>
      <button @click="resetError">Try again</button>
    </template>
    <template v-else>
      <slot></slot>
    </template>
  </div>
</template>

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

const error = ref(null);

onErrorCaptured((err, instance, info) => {
  console.error('Caught an error:', err, instance, info);
  error.value = err;
  // Return false to stop the error from propagating further up the component tree
  return false;
});

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

<style scoped>
.error-boundary {
  border: 1px solid #ff0000;
  padding: 10px;
  margin: 10px 0;
  background-color: #ffeaea;
  color: #cc0000;
  border-radius: 4px;
}
.error-message {
  font-weight: bold;
}
</style>

<!-- BuggyComponent.vue -->
<template>
  <div>
    <h3>Buggy Component</h3>
    <button @click="throwError">Trigger Error</button>
  </div>
</template>

<script setup>
const throwError = () => {
  throw new Error('This is an intentional error from BuggyComponent!');
};
</script>

<!-- App.vue -->
<template>
  <div>
    <h1>Application with Error Boundary</h1>
    <p>Content above error boundary</p>
    <ErrorBoundary>
      <BuggyComponent />
    </ErrorBoundary>
    <p>Content below error boundary (should still render)</p>
  </div>
</template>

<script setup>
import ErrorBoundary from './ErrorBoundary.vue';
import BuggyComponent from './BuggyComponent.vue';
</script>
How it works: The `onErrorCaptured` lifecycle hook in Vue 3 allows you to catch errors that occur within a component's descendant tree. This snippet demonstrates creating an `ErrorBoundary` component that wraps other components. If an error is thrown in a child (like `BuggyComponent`), `onErrorCaptured` intercepts it, allowing the `ErrorBoundary` to display a fallback UI instead of crashing the entire application, making your Vue apps more resilient. Returning `false` from `onErrorCaptured` prevents the error from propagating further up the component tree.

Need help integrating this into your project?

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

Hire DigitalCodeLabs