Vue3捕獲和處理不同層級(jí)的異常/錯(cuò)誤的有效方法
引言
項(xiàng)目中如果沒有對(duì)異常做處理,可能導(dǎo)致應(yīng)用崩潰或顯示報(bào)錯(cuò)信息影響用戶體驗(yàn)。因此需要對(duì)不同層級(jí)的錯(cuò)誤進(jìn)行捕獲,確保用戶即使在錯(cuò)誤發(fā)生時(shí)仍能使用應(yīng)用的其他功能或者能查看到更友好的提示消息。
組件級(jí)異常捕獲:
- 單組件 使用 errorCaptured 鉤子來捕獲單一組件中的錯(cuò)誤。
<template>
<button @click="test">拋出錯(cuò)誤</button>
</template>
<script setup lang="ts">
const test = () => {
throw 'error'
}
onErrorCaptured((err, instance, info)=>{
console.log('錯(cuò)誤:',err, instance, info)
})
</script>
- 多組件(跨多個(gè)組件的錯(cuò)誤邊界)
使用方式:
// 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>
實(shí)現(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(
"[捕獲錯(cuò)誤]",
err.message,
"vm",
vm,
"info",
info,
window.history
);
isError.value = true;
return false; // onErrorCaptured 早于window.onerror 等執(zhí)行,這里捕獲了返回false就不會(huì)向上繼續(xù)拋出了
});
const handleErrorChange = (isError: boolean) => {
if (!isError) {
// 在這里進(jìn)行錯(cuò)誤處理
// router.push("/").then(() => {
// location.reload();
// });
}
};
</script>
全局異常捕獲
- 使用 app.config.errorHandler 設(shè)置全局錯(cuò)誤處理器來捕獲未通過組件級(jí)別捕獲的錯(cuò)誤。
import { createApp } from "vue";
import App from "./App.vue";
const app = createApp(App);
app.config.errorHandler = (err, instance, info) => {
// 這里可以執(zhí)行全局的錯(cuò)誤處理邏輯,比如上報(bào)服務(wù)器
console.error('Global error handler:', err, { instance, info });
};
- 通過window事件捕獲 可以添加全局的 window 事件來捕獲未處理的錯(cuò)誤和未捕獲的 Promise 異常。
window.addEventListener(
"error",
(e) => {
console.log("全局報(bào)錯(cuò)捕獲", e);
return true;
},
true
);
// 處理未捕獲的異常,主要是promise內(nèi)部異常,統(tǒng)一拋給 onerror
window.addEventListener("unhandledrejection", (e) => {
throw e.reason;
});
代碼級(jí)局部捕獲
使用 try-catch 捕獲異步或特定代碼塊中的錯(cuò)誤。
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);
// 局部錯(cuò)誤處理邏輯
}
};
總結(jié)
通過以上幾種方法,可以在 Vue 3 項(xiàng)目中可以有效地捕獲和處理不同層級(jí)的錯(cuò)誤,從而提升用戶體驗(yàn)。
到此這篇關(guān)于Vue3捕獲和處理不同層級(jí)的異常/錯(cuò)誤的有效方法的文章就介紹到這了,更多相關(guān)Vue3捕獲和處理不同層級(jí)錯(cuò)誤內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解vue-cli之webpack3構(gòu)建全面提速優(yōu)化
這篇文章主要介紹了詳解vue-cli之webpack3構(gòu)建全面提速優(yōu)化,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-12-12
在Vue前端(Vue2/Vue3?通用)載入JSON格式的動(dòng)圖實(shí)例代碼
這篇文章主要介紹了在Vue前端(Vue2/Vue3?通用)載入JSON格式動(dòng)圖的相關(guān)資料,文中通過代碼講解了環(huán)境配置、組件集成、動(dòng)畫控制等,重點(diǎn)介紹了Lottie的loadAnimation方法的參數(shù)配置和常見問題解決方法,需要的朋友可以參考下2025-11-11
一文教會(huì)你搭建vite項(xiàng)目并配置路由和element-plus
由于項(xiàng)目搭建過程實(shí)在繁瑣,容易遺忘,每次新建項(xiàng)目還得百度一下怎么搭建,所以寫下本文提醒自己,下面這篇文章主要給大家介紹了關(guān)于搭建vite項(xiàng)目并配置路由和element-plus的相關(guān)資料,需要的朋友可以參考下2022-07-07
詳解Vue 多級(jí)組件透?jìng)餍路椒╬rovide/inject
這篇文章主要介紹了詳解Vue 多級(jí)組件透?jìng)餍路椒╬rovide/inject,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-05-05
vue結(jié)合leaflet實(shí)現(xiàn)熱力圖
本文主要介紹了vue實(shí)現(xiàn)熱力圖,結(jié)合leaflet.heat插件可以很容易的做出熱力圖,文中通過示例代碼介紹的非常詳細(xì),需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06

