N
Nuxt3mo ago
TRex

Component-Based Error Handling (SSR)?

<NuxtErrorBoundry> component handles client-side errors happening in its default slot. But its not works on ssr. We are getting the ugly error page if the page that contains error is rendered on SSR. I want to my whole page to be rendered except the component that throws an err. Is there any way to handle this?
2 Replies
Cue
Cue3mo ago
There’s a few workarounds in this issue https://github.com/nuxt/nuxt/issues/15781
GitHub
Bug: Handling errors with the NuxtErrorBoundary component · Issue #...
The NuxtErrorBoundary component does not seem to work as expected: The #error slot will receive error as a prop. (If you set error = null it will trigger re-rendering the default slot; Example: // ...
TRex
TRex3mo ago
For those who looks for a solution, this works perfect on both csr and ssr!!! components/ErrorBoundary.vue
<script setup lang="ts">
const error = ref<Error>()

function clearError() {
error.value = undefined
}

onErrorCaptured(err => {
error.value = err
return false
})

const route = useRoute()
watch(
() => route.fullPath,
() => {
error.value = undefined
},
)
</script>

<template>
<slot v-if="!error" />
<slot v-else name="error" :error="error" :clear-error="clearError" />
</template>
<script setup lang="ts">
const error = ref<Error>()

function clearError() {
error.value = undefined
}

onErrorCaptured(err => {
error.value = err
return false
})

const route = useRoute()
watch(
() => route.fullPath,
() => {
error.value = undefined
},
)
</script>

<template>
<slot v-if="!error" />
<slot v-else name="error" :error="error" :clear-error="clearError" />
</template>
How to use
<error-boundary>
<nuxt-page v-bind="$attrs" />
<template #error="{ error, clearError }">
<p>{{ error }}</p>
<button @click="clearError">Try again</button>
</template>
</error-boundary>
<error-boundary>
<nuxt-page v-bind="$attrs" />
<template #error="{ error, clearError }">
<p>{{ error }}</p>
<button @click="clearError">Try again</button>
</template>
</error-boundary>
Source https://github.com/nuxt/nuxt/issues/15781#issuecomment-1592681048