Features
5. Error Handling
Handle errors in page interactions and data communications to improve user experience.
Introduction
For error handling, I have implemented the following:
- Use Winston to log to files
- Set up error.vue as global error page
- Configure auth/error.vue for authentication error page
Winston Logging
Configure nuxt.config.ts, log files are written to the /logs directory.
nuxt3WinstonLog: {
maxSize: '2048m',
maxFiles: '7d',
infoLogPath: `./logs`,
infoLogName: `%DATE%-${process.env.NODE_ENV}-info.log`,
errorLogPath: `./logs`,
errorLogName: `%DATE%-${process.env.NODE_ENV}-error.log`,
skipRequestMiddlewareHandler: false
},
Logs expire after 7 days.
error.vue Global Error Page
When an error occurs, Nuxt will automatically redirect to error.vue. The script below will display an error message page and guide users to return to the homepage for their next action.
<template>
<div>
<AppHeader />
<UMain>
<UContainer>
<UPage>
<UPageError :error="error" />
</UPage>
</UContainer>
</UMain>
<AppFooter />
<ClientOnly>
<LazyUContentSearch :files="files" :navigation="navigation" />
</ClientOnly>
<UNotifications />
</div>
</template>
auth/error.vue Authentication Error Page
When the next-auth component encounters an error, it will redirect to app/pages/auth/error.vue. It will pass an error parameter, which we need to display in a user-friendly way and guide users to log in again.
<script setup lang="ts">
const route = useRoute()
const errorCode = computed(() => route.params.error)
const page = {
title: 'Authentication Error',
description: 'Please click return to login or register again.'
}
...
</script>
<template>
<UContainer>
<UPageHeader v-bind="page" class="py-[50px]" />
<UPageBody>
<div>
<h2>User Authentication Error {{ errorCode }}. Please try again!</h2>
<NuxtLink to="/" class="text-blue-500"> Return to Homepage </NuxtLink>
</div>
</UPageBody>
</UContainer>
</template>
end