68
Vue 3 學習之旅
錯誤處理
Day 68: 錯誤處理:onErrorCaptured
·6 分鐘閱讀·錯誤處理
摘要
onErrorCaptured
是一個生命週期鉤子,它能捕獲來自其所有後代元件(無論層級多深)中拋出的錯誤。
定義與說明
在一個父元件中使用 onErrorCaptured
鉤子,可以建立一個「錯誤邊界」(Error Boundary)。當任何子元件出現錯誤時,這個鉤子會被觸發,接收到錯誤物件、出錯的元件實例和錯誤資訊。你可以在此處記錄錯誤、顯示一個備用的 UI,並透過回傳 false 來阻止錯誤繼續向上傳播。
實作範例
Vue SFC
<!-- ErrorBoundary.vue -->
<script setup>
import { ref, onErrorCaptured } from 'vue';
const error = ref(null);
onErrorCaptured((err, instance, info) => {
error.value = err;
console.error('捕獲到錯誤:', err, info);
return false; // 阻止錯誤繼續冒泡
});
</script>
<template>
<div v-if="error">糟糕,出錯了!</div>
<slot v-else></slot>
</template>
結論
onErrorCaptured
是構建健墯、有彈性的 Vue 應用的關鍵。它能有效隔離單一元件的錯誤,防止整個應用程式因局部問題而崩潰。
錯誤處理 onErrorCaptured 錯誤邊界