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>
實現方式:
// 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內部異常,統一拋給 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中使用gantt-elastic實現可拖拽甘特圖的示例代碼
這篇文章主要介紹了vue中使用gantt-elastic實現可拖拽甘特圖,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-07-07Vue?前端路由工作原理hash與history的區(qū)別
這篇文章主要介紹了Vue?前端路由工作原理hash與history的區(qū)別,文章圍繞主題展開vue-router的工作原理的簡單介紹,感興趣的朋友可以學習一下2022-07-07