文章目录
写代码最怕什么?不是写不出来,而是写出来后用户一操作就崩了。页面白屏、接口报错、路由找不到……这些问题如果处理不好,用户体验会非常糟糕。今天我们来学习 Nuxt 的错误处理机制,给应用装上"安全气囊"。
一、全局错误页面
当用户访问不存在的页面时,需要展示一个友好的 404 页面。Nuxt 让这件事变得很简单。
创建 error.vue(注意:在项目根目录,不是 pages 目录):
<script setup lang="ts">
const props = defineProps<{
error: {
url: string
statusCode: number
statusMessage: string
message: string
}
}>()
const handleError = () => clearError({ redirect: '/' })
</script>
<template>
<div class="error-page">
<h1>{
{ error.statusCode }}</h1>
<p>{
{ error.statusMessage || '出错了' }}</p>
<button @click="handleError">返回首页</button>
</div>
</template>
<style scoped>
.error-page {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 100vh;
text-align: center;
}
h1 {
font-size: 6rem;
color: #00dc82;
margin-bottom: 1rem;
}
p {
font-size: 1.5rem;
color: #666;
margin-bottom: 2rem;
}
button {
padding: 0.75rem 1.5rem;
background: #00dc82;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 1rem;
}
button:hover {
background: #00b36b;
}
</style>
现在访问一个不存在的路由,比如 /abcdefg,就会显示这个错误页面。
二、针对不同错误码显示不同内容
404、500、403……不同的错误应该有不同的提示。优化一下:
<script setup lang="ts">
const props = defineProps<{
error: {
statusCode: number
message: string
}
}>()
// 根据错误码返回提示信息
const errorInfo = computed(() => {
const errors: Record<number, { title: string; desc: string }> = {
404: { title: '页面走丢了', desc: '您访问的页面不存在' },
403: { title: '禁止访问', desc: '您没有权限访问此页面' },
500: { title: '服务器开小差了', desc: '请稍后再试' }
}
return errors[props.error.statusCode] || {
title: '出错了',
desc: props.error.message
}
})
const goHome = () => clearError({ redirect: '/' })
const goBack = () => clearError()
</script>
<template>
<div class="error-page">
<h1>{
{ error.statusCode }}</h1>
<h2>{
{ errorInfo.title }}</h2>
<p>{
{ errorInfo.desc }}</p>
<div class="actions">
<button @click="goBack">返回上一页</button>
<button class="primary" @click="goHome">返回首页</button>
</div>
</div&


1333

被折叠的 条评论
为什么被折叠?



