Vue3捕獲和處理不同層級的異常/錯誤的有效方法
更新時間:2025年01月20日 11:04:57 作者:Turtle
項目中如果沒有對異常做處理,可能導致應用崩潰或顯示報錯信息影響用戶體驗,因此需要對不同層級的錯誤進行捕獲,所以本文給大家介紹了Vue3捕獲和處理不同層級的異常/錯誤的有效方法,需要的朋友可以參考下
引言
項目中如果沒有對異常做處理,可能導致應用崩潰或顯示報錯信息影響用戶體驗。因此需要對不同層級的錯誤進行捕獲,確保用戶即使在錯誤發(fā)生時仍能使用應用的其他功能或者能查看到更友好的提示消息。
組件級異常捕獲:
- 單組件 使用 errorCaptured 鉤子來捕獲單一組件中的錯誤。
<template>
<button @click="test">拋出錯誤</button>
</template>
<script setup lang="ts">
const test = () => {
throw 'error'
}
onErrorCaptured((err, instance, info)=>{
console.log('錯誤:',err, instance, info)
})
</script>
- 多組件(跨多個組件的錯誤邊界)
使用方式:
// index.vue
<template>
<ErrorBoundary>
<router-view v-slot="{ Component, route }">
<template v-if="Component">
<component :is="Component" :key="route.name" />
</template>
</router-view>
</ErrorBoundary>
</template>
<script setup lang="ts">
import ErrorBoundary from "@/components/error/ErrorBoundary.vue";
</script>
實現(xiàn)方式:
// 404.vue
<template>
<el-result
status="404"
title="404"
sub-title="Sorry, the page you visited does not exist."
>
<template #extra>
<a-button type="primary" @click="onChange"> 回到首頁 </a-button>
</template>
</el-result>
</template>
<script lang="ts">
export default {
name: "NotFound",
};
</script>
<script lang="ts" setup>
import { defineEmits } from "vue";
const emit = defineEmits(["change"]);
const onChange = () => {
emit("change", false);
};
</script>
// ErrorBoundary.vue
<template>
<div v-if="isError">
<NotFound @change="handleErrorChange" />
</div>
<div v-else>
<slot></slot>
</div>
</template>
<script setup lang="ts">
import router from "@/router";
import NotFound from "@/components/error/404.vue";
import { onErrorCaptured, ref } from "vue";
const isError = ref(false);
onErrorCaptured((err, vm, info) => {
console.error(
"[捕獲錯誤]",
err.message,
"vm",
vm,
"info",
info,
window.history
);
isError.value = true;
return false; // onErrorCaptured 早于window.onerror 等執(zhí)行,這里捕獲了返回false就不會向上繼續(xù)拋出了
});
const handleErrorChange = (isError: boolean) => {
if (!isError) {
// 在這里進行錯誤處理
// router.push("/").then(() => {
// location.reload();
// });
}
};
</script>
全局異常捕獲
- 使用 app.config.errorHandler 設置全局錯誤處理器來捕獲未通過組件級別捕獲的錯誤。
import { createApp } from "vue";
import App from "./App.vue";
const app = createApp(App);
app.config.errorHandler = (err, instance, info) => {
// 這里可以執(zhí)行全局的錯誤處理邏輯,比如上報服務器
console.error('Global error handler:', err, { instance, info });
};
- 通過window事件捕獲 可以添加全局的 window 事件來捕獲未處理的錯誤和未捕獲的 Promise 異常。
window.addEventListener(
"error",
(e) => {
console.log("全局報錯捕獲", e);
return true;
},
true
);
// 處理未捕獲的異常,主要是promise內部異常,統(tǒng)一拋給 onerror
window.addEventListener("unhandledrejection", (e) => {
throw e.reason;
});
代碼級局部捕獲
使用 try-catch 捕獲異步或特定代碼塊中的錯誤。
const fetchData = async () => {
try {
const response = await fetch('https://api.example.com/data');
result.value = await response.json();
} catch (error) {
console.error('Error fetching data:', error);
// 局部錯誤處理邏輯
}
};
總結
通過以上幾種方法,可以在 Vue 3 項目中可以有效地捕獲和處理不同層級的錯誤,從而提升用戶體驗。
到此這篇關于Vue3捕獲和處理不同層級的異常/錯誤的有效方法的文章就介紹到這了,更多相關Vue3捕獲和處理不同層級錯誤內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
詳解vue-cli之webpack3構建全面提速優(yōu)化
這篇文章主要介紹了詳解vue-cli之webpack3構建全面提速優(yōu)化,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-12-12
在Vue前端(Vue2/Vue3?通用)載入JSON格式的動圖實例代碼
這篇文章主要介紹了在Vue前端(Vue2/Vue3?通用)載入JSON格式動圖的相關資料,文中通過代碼講解了環(huán)境配置、組件集成、動畫控制等,重點介紹了Lottie的loadAnimation方法的參數(shù)配置和常見問題解決方法,需要的朋友可以參考下2025-11-11
一文教會你搭建vite項目并配置路由和element-plus
由于項目搭建過程實在繁瑣,容易遺忘,每次新建項目還得百度一下怎么搭建,所以寫下本文提醒自己,下面這篇文章主要給大家介紹了關于搭建vite項目并配置路由和element-plus的相關資料,需要的朋友可以參考下2022-07-07

