error.vue

error.vue 文件是 Nuxt 应用中的错误页面。

在应用的生命周期中,运行时可能会出现一些意外错误。在这种情况下,我们可以使用 error.vue 文件覆盖默认错误文件并美观地显示错误。

¥During the lifespan of your application, some errors may appear unexpectedly at runtime. In such case, we can use the error.vue file to override the default error files and display the error nicely.

error.vue
<script setup lang="ts">
import type { NuxtError } from '#app'

const props = defineProps({
  error: Object as () => NuxtError
})
</script>

<template>
  <div>
    <h1>{{ error.statusCode }}</h1>
    <NuxtLink to="/">Go back home</NuxtLink>
  </div>
</template>
虽然它被称为 'error page',但它不是路由,不应放在 ~/pages 目录中。出于同样的原因,你不应在此页面中使用 definePageMeta。话虽如此,你仍然可以在错误文件中使用布局,方法是使用 NuxtLayout 组件并指定布局名称。

错误页面只有一个 prop - error 包含需要你处理的错误。

¥The error page has a single prop - error which contains an error for you to handle.

error 对象提供以下字段:

¥The error object provides the following fields:

{
  statusCode: number
  fatal: boolean
  unhandled: boolean
  statusMessage?: string
  data?: unknown
  cause?: unknown
}

如果你的自定义字段出现错误,它们将会丢失;你应该将它们赋值给 data

¥If you have an error with custom fields they will be lost; you should assign them to data instead:

throw createError({
  statusCode: 404,
  statusMessage: 'Page Not Found',
  data: {
    myCustomField: true
  }
})