Intermediate LevelVue JS
How do you combine <Suspense> with onErrorCaptured to build robust async error boundaries?
❓ Interview Prompt: Explain combining <Suspense> and onErrorCaptured, handling failed async setup data fetches, and rendering fallback cards.
If an async component inside a '<Suspense>' default slot fails to resolve its top-level 'await' network fetch, '<Suspense>' remains stuck or crashes.
The Async Error Boundary Pattern:
Wrap '<Suspense>' inside a dedicated Error Boundary parent component that implements 'onErrorCaptured()'. If the async data fetch fails, the parent catches the exception and renders an Error Card fallback UI!
Code Implementation Example
html
<script setup>
import { ref, onErrorCaptured } from 'vue';
const hasFetchError = ref(false);
onErrorCaptured(() => {
hasFetchError.value = true;
return false; // Trap error inside boundary!
});
</script>
<template>
<div v-if="hasFetchError" class="error-card">Failed to load async data!</div>
<Suspense v-else>
<template #default><AsyncDataWidget /></template>
<template #fallback><div>Loading...</div></template>
</Suspense>
</template>💡Building an async error boundary combining Suspense with onErrorCaptured.
🎯 Interview Key Takeaway
Wrap <Suspense> inside an onErrorCaptured error boundary component to handle failed async setup data fetches gracefully.
#Suspense#onErrorCaptured#Error Boundary#Intermediate
Back to all Vue JS Questions→