引言
项目中如果没有对异常做处理,可能导致应用崩溃或显示报错信息影响用户体验。因此需要对不同层级的错误进行捕获,确保用户即使在错误发生时仍能使用应用的其他功能或者能查看到更友好的提示消息。
组件级异常捕获:
- 单组件 使用 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 等执行,这里捕获了返回false就不会向上继续抛出了 }); 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) => { // 这里可以执行全局的错误处理逻辑,比如上报服务器 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捕获和处理不同层级错误内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论