Error Handling
As Nuxt is a full-stack framework, various errors are expected to occur on both the client-side and server-side.
Implementing proper error handling can improve the user experience.
Common Error Patterns
1. 404 Not Found Errors
- When accessing a non-existent page
- When invalid parameters are passed to dynamic routes
2. Data Fetching Errors
- When an unexpected response is returned from an API
- When network errors occur
- When authentication errors occur
3. Server Errors
- When errors occur within the server
- Database connection errors, etc.
Error Handling Methods
Using the createError Function
In Nuxt, you can handle errors using the createError function.
<script setup lang="ts">
const { data } = await $fetch('/api/user/123')
if (!data) {
throw createError({
statusCode: 404,
statusMessage: 'Page not found'
})
}
</script>
Using the showError Function
You can also display errors using the showError function.
<script setup lang="ts">
try {
const data = await $fetch('/api/data')
}
catch (error) {
showError({
statusCode: 500,
statusMessage: 'Failed to fetch data'
})
}
</script>
Difference between createError and showError
createError: Creates an error object and is used in combination withthrow. It completely stops page loading and transitions to an error page. Works on both server-side and client-side.showError: Stops displaying the current page and shows an error page, but doesn't requirethrow. Suitable for error handling during asynchronous processing mainly on the client-side.
clearError Function
To return from an error page to a normal page, use the clearError function.
<script setup lang="ts">
const handleError = () => clearError({ redirect: '/' })
</script>
<template>
<button type="button" @click="handleError">
Clear errors
</button>
</template>
Creating a Custom Error Page
You can implement a custom error page by creating an error.vue file in the root directory of your project.
<script setup lang="ts">
import type { NuxtError } from '#app'
const props = defineProps({
error: Object as () => NuxtError,
})
const handleError = () => clearError({ redirect: '/' })
</script>
<template>
<div>
<h1>{{ error.statusCode }}</h1>
<p>{{ error.message }}</p>
<button type="button" @click="handleError">
Clear errors
</button>
</div>
</template>
Challenge
- Throw an error
In the script section ofpages/todo/[id].vue, add code that usescreateErrortothrowa 404 error when there is no data to display. - Verify error page behavior
When passing a non-existent id, verify that the custom error page displays a 404 error.