進階架構
ResilienceUX

錯誤處理

在全端應用程式中,錯誤可能發生在伺服器端 (API, Middleware) 或客戶端 (Vue Components)。Nuxt 提供了一套完整的機制來捕捉並優雅地處理這些錯誤。

錯誤處理流程

理解錯誤發生的位置至關重要。伺服器端錯誤通常需要顯示全頁錯誤畫面 (Full Page Error),而客戶端錯誤則可以透過錯誤邊界 (Error Boundary) 進行局部處理,避免整個頁面崩潰。

// Code Example
Select a scenario...
User Action
API / Server
Page / Component
error.vue
<NuxtErrorBoundary>

拋出錯誤

使用 createError 來建立錯誤物件。這在 API 路由或 Middleware 中特別有用。

server/api/test.ts
server/api/test.ts
export default defineEventHandler((event) => {
  const id = getRouterParam(event, 'id')

  if (!id) {
    throw createError({
      statusCode: 400,
      statusMessage: 'ID is required'
    })
  }
})

createError vs showError

  • createError: 建立錯誤物件,通常用於 throw 或返回。
  • showError: 立即導航到錯誤頁面 (Client-side)。

錯誤邊界

<NuxtErrorBoundary> 允許你捕捉元件樹中的錯誤,並顯示備用 UI (Fallback),而不是讓整個應用程式崩潰。

<template>
  <NuxtErrorBoundary>
    <!-- 可能出錯的元件 -->
    <VideoPlayer />

    <!-- 錯誤發生時顯示的內容 -->
    <template #error="{ error, clearError }">
      <div class="error-card">
        <p>影片載入失敗: {{ error.message }}</p>
        <button @click="clearError">重試</button>
      </div>
    </template>
</NuxtErrorBoundary>
</template>

全域錯誤頁面

當發生未捕獲的致命錯誤 (Fatal Error) 時,Nuxt 會渲染 error.vue。 這是一個位於專案根目錄的特殊頁面。

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

const props = defineProps<{
  error: NuxtError
}>()

const handleError = () => clearError({ redirect: '/' })
</script>

<template>
  <div class="h-screen flex flex-col items-center justify-center">
    <h1 class="text-9xl font-bold text-emerald-500">{{ error.statusCode }}</h1>
    <p class="text-xl text-slate-400 mt-4">{{ error.statusMessage }}</p>
    <button @click="handleError" class="mt-8 btn-primary">
      Go Home
    </button>
  </div>
</template>