Handling errors for your Nuxt 3 app
I'll show you how to handle the errors for your Nuxt 3 app.
Introduction
👋 Hi all, we will be extending our blog to add customized error page in our app. We will be using the Nuxt blog we created in this article. You can download the source code there and this is what we will accomplish by the end of this article.
Custom Error Page
Let's begin by creating a custom error page error.vue
under our project root folder. Our Nuxt app will display this error page whenever it encounters a fatal error.
~/error.vue<script setup lang="ts">defineProps({ error: Object,});function handleError() { clearError({ redirect: "/" });}</script><template> <NuxtLayout> <div class="container prose mx-auto my-16 text-center dark:prose-invert"> <h1>Error {{ error?.statusCode }}</h1> <p class="mb-2">{{ error?.message }}</p> <p class="mt-2">It looks like there's an error 😱</p> <button @click.prevent="handleError" class="rounded-lg px-6 py-3 transition-colors hover:bg-gray-100 dark:hover:bg-gray-800"> Go back to home </button> </div> </NuxtLayout></template>
Our error page receive a error
prop object where we retrieve the error message and status code to display a helpful information and a button that leads them back to the home page. Our button uses the clearError function from Nuxt to clear the currently handled error and redirect them back to the home page.
✨ With this we have completed our error page!
Triggering Errors for ContentDoc
If you are following us from our creating a blog articles, you will notice that when you visit an invalid path such as http://localhost:3000/404, you are not redirected to the custom error page and you see the Document not found,... message.
This is an intended feature by ContentDoc when no article is found. We can change that by adding the code below to our catch-all-route under the /pages/[...slug.vue]
file.
//pages/[...slug.vue]<script setup lang="ts">const { path } = useRoute();const { data: article } = await useAsyncData(`article-${path}`, () => queryContent(path).count() //retrieve our article under this path);if (!article.value) { //throw a 404 error if our article is not found throw createError({ statusCode: 404 });}</script><template> <!-- rest of the code... --></template>
Using the path retrieved from useRoute, we check if it exists using queryContent.
If the path is invalid, we throw a 404 error using createError and this will redirect the viewers to our custom error page.
✨ You have now learned how to create a custom error page and trigger an error to it!
What's next?
Download the complete code here at Github.
Check out more related articles below!
Create a Nuxt 3 Content blog with Tailwind CSS in one hour.
Add dark mode to your Nuxt 3 app in 15 mins.
Add table of contents to your Nuxt 3 blog in 10 mins.