Vue3捕獲和處理不同層級(jí)的異常/錯(cuò)誤的有效方法
引言
項(xiàng)目中如果沒(méi)有對(duì)異常做處理,可能導(dǎo)致應(yīng)用崩潰或顯示報(bào)錯(cuò)信息影響用戶體驗(yàn)。因此需要對(duì)不同層級(jí)的錯(cuò)誤進(jìn)行捕獲,確保用戶即使在錯(cuò)誤發(fā)生時(shí)仍能使用應(yīng)用的其他功能或者能查看到更友好的提示消息。
組件級(jí)異常捕獲:
- 單組件 使用 errorCaptured 鉤子來(lái)捕獲單一組件中的錯(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"> 回到首頁(yè) </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ò)誤處理器來(lái)捕獲未通過(guò)組件級(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 }); };
- 通過(guò)window事件捕獲 可以添加全局的 window 事件來(lái)捕獲未處理的錯(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é)
通過(guò)以上幾種方法,可以在 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)文章
el-table樹(shù)形數(shù)據(jù)序號(hào)排序處理方案
這篇文章主要介紹了el-table樹(shù)形數(shù)據(jù)序號(hào)排序處理方案,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2024-03-03vue中使用gantt-elastic實(shí)現(xiàn)可拖拽甘特圖的示例代碼
這篇文章主要介紹了vue中使用gantt-elastic實(shí)現(xiàn)可拖拽甘特圖,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-07-07vue使用@include或@mixin報(bào)錯(cuò)的問(wèn)題及解決
這篇文章主要介紹了vue使用@include或@mixin報(bào)錯(cuò)的問(wèn)題及解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-02-02Vue3使用Signature Pad實(shí)現(xiàn)電子簽名功能
Vue3簽名板是一種在Vue3應(yīng)用中實(shí)現(xiàn)用戶簽名功能的組件,Vue3-signature-pad的實(shí)現(xiàn)旨在為開(kāi)發(fā)者提供一個(gè)簡(jiǎn)單易用的工具,使用戶能夠在前端界面上進(jìn)行簽名操作,常見(jiàn)于電子商務(wù)、電子合同等場(chǎng)景,本文介紹了Vue3使用Signature Pad實(shí)現(xiàn)電子簽名功能,需要的朋友可以參考下2025-04-04Vue?前端路由工作原理hash與history的區(qū)別
這篇文章主要介紹了Vue?前端路由工作原理hash與history的區(qū)別,文章圍繞主題展開(kāi)vue-router的工作原理的簡(jiǎn)單介紹,感興趣的朋友可以學(xué)習(xí)一下2022-07-07vue自定義指令實(shí)現(xiàn)一鍵復(fù)制功能
本文旨在記錄解決在工作中一鍵復(fù)制功能得需求,本文主要使用了Vue3+TypeScript+Ant-Design-Vue,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-11-11