Vue3捕獲和處理不同層級的異常/錯誤的有效方法
引言
項(xiàng)目中如果沒有對異常做處理,可能導(dǎo)致應(yīng)用崩潰或顯示報錯信息影響用戶體驗(yàn)。因此需要對不同層級的錯誤進(jìn)行捕獲,確保用戶即使在錯誤發(fā)生時仍能使用應(yīng)用的其他功能或者能查看到更友好的提示消息。
組件級異常捕獲:
- 單組件 使用 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>
實(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( "[捕獲錯誤]", 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) { // 在這里進(jìn)行錯誤處理 // router.push("/").then(() => { // location.reload(); // }); } }; </script>
全局異常捕獲
- 使用 app.config.errorHandler 設(shè)置全局錯誤處理器來捕獲未通過組件級別捕獲的錯誤。
import { createApp } from "vue"; import App from "./App.vue"; const app = createApp(App); app.config.errorHandler = (err, instance, info) => { // 這里可以執(zhí)行全局的錯誤處理邏輯,比如上報服務(wù)器 console.error('Global error handler:', err, { instance, info }); };
- 通過window事件捕獲 可以添加全局的 window 事件來捕獲未處理的錯誤和未捕獲的 Promise 異常。
window.addEventListener( "error", (e) => { console.log("全局報錯捕獲", e); return true; }, true ); // 處理未捕獲的異常,主要是promise內(nèi)部異常,統(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); // 局部錯誤處理邏輯 } };
總結(jié)
通過以上幾種方法,可以在 Vue 3 項(xiàng)目中可以有效地捕獲和處理不同層級的錯誤,從而提升用戶體驗(yàn)。
到此這篇關(guān)于Vue3捕獲和處理不同層級的異常/錯誤的有效方法的文章就介紹到這了,更多相關(guān)Vue3捕獲和處理不同層級錯誤內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue中使用gantt-elastic實(shí)現(xiàn)可拖拽甘特圖的示例代碼
這篇文章主要介紹了vue中使用gantt-elastic實(shí)現(xiàn)可拖拽甘特圖,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-07-07Vue3使用Signature Pad實(shí)現(xiàn)電子簽名功能
Vue3簽名板是一種在Vue3應(yīng)用中實(shí)現(xiàn)用戶簽名功能的組件,Vue3-signature-pad的實(shí)現(xiàn)旨在為開發(fā)者提供一個簡單易用的工具,使用戶能夠在前端界面上進(jìn)行簽名操作,常見于電子商務(wù)、電子合同等場景,本文介紹了Vue3使用Signature Pad實(shí)現(xiàn)電子簽名功能,需要的朋友可以參考下2025-04-04Vue?前端路由工作原理hash與history的區(qū)別
這篇文章主要介紹了Vue?前端路由工作原理hash與history的區(qū)別,文章圍繞主題展開vue-router的工作原理的簡單介紹,感興趣的朋友可以學(xué)習(xí)一下2022-07-07vue自定義指令實(shí)現(xiàn)一鍵復(fù)制功能
本文旨在記錄解決在工作中一鍵復(fù)制功能得需求,本文主要使用了Vue3+TypeScript+Ant-Design-Vue,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-11-11