0
0
Vueframework~30 mins

Error boundaries with onErrorCaptured in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Error boundaries with onErrorCaptured in Vue
📖 Scenario: You are building a Vue app that shows user profiles. Sometimes, a profile might have missing or broken data that causes errors. You want to catch these errors gracefully and show a friendly message instead of a broken page.
🎯 Goal: Create a Vue component that uses onErrorCaptured to catch errors from a child component and display a fallback message.
📋 What You'll Learn
Create a child component called UserProfile that throws an error when the user prop is missing.
Create a parent component called ErrorBoundary that uses onErrorCaptured to catch errors from UserProfile.
Show a fallback message inside ErrorBoundary when an error is caught.
Pass a user prop to UserProfile from ErrorBoundary.
💡 Why This Matters
🌍 Real World
Error boundaries help keep your app running smoothly by catching unexpected errors in parts of your UI and showing friendly messages instead of crashing the whole page.
💼 Career
Understanding error boundaries is important for building robust Vue applications that handle failures gracefully and improve user experience.
Progress0 / 4 steps
1
Create the UserProfile component
Create a Vue component called UserProfile that accepts a prop named user. If user is not provided, throw an error with the message 'User data is missing'. Otherwise, render a <div> showing User: {{ user.name }}.
Vue
Hint

Use defineProps to declare the user prop. Check if user is missing and throw an error. Render the user's name inside a <div>.

2
Create the ErrorBoundary component setup
Create a Vue component called ErrorBoundary. Inside <script setup>, import ref and onErrorCaptured from 'vue'. Create a reactive variable called error initialized to null. Use onErrorCaptured to catch errors and set error.value to the error message.
Vue
Hint

Use ref(null) to create error. Use onErrorCaptured callback to catch errors and update error.value.

3
Render UserProfile and show fallback on error
Inside the ErrorBoundary template, use a <template> with v-if to show a <div> with text 'Error: ' + error if error is not null. Otherwise, render the UserProfile component and pass a user prop with value { name: 'Alice' }. Import UserProfile at the top.
Vue
Hint

Use v-if to show the error message. Use v-else to show UserProfile with the user prop.

4
Test error handling by passing no user
Modify the ErrorBoundary template to render UserProfile without the user prop to trigger the error. Keep the error message display logic unchanged.
Vue
Hint

Remove the user prop from UserProfile to cause the error and see the fallback message.