vue实现页面500
Vue 实现页面 500 错误处理
在 Vue 项目中,可以通过全局错误处理或组件级错误捕获来实现 500 错误的展示与处理。以下是具体实现方法:
全局错误处理
通过 Vue 的全局错误处理器 errorHandler 捕获未处理的异常,并跳转到自定义 500 页面:
// main.js 或入口文件
Vue.config.errorHandler = (err, vm, info) => {
console.error('全局错误:', err)
router.push('/500') // 跳转到 500 页面
}
路由级错误处理
在 Vue Router 中配置全局前置守卫和错误捕获:
// router.js
router.beforeEach((to, from, next) => {
// 模拟 API 请求失败
if (to.meta.requiresAuth && !isAuthenticated()) {
next('/500')
} else {
next()
}
})
router.onError((error) => {
console.error('路由错误:', error)
router.push('/500')
})
自定义 500 页面组件
创建专门的错误页面组件:
<!-- components/Error500.vue -->
<template>
<div class="error-page">
<h1>500 - 服务器内部错误</h1>
<p>抱歉,服务器处理您的请求时出现问题</p>
<button @click="goHome">返回首页</button>
</div>
</template>
<script>
export default {
methods: {
goHome() {
this.$router.push('/')
}
}
}
</script>
Axios 拦截器处理
对于 API 请求的 500 错误,可以通过 Axios 拦截器统一处理:
// utils/http.js
axios.interceptors.response.use(
response => response,
error => {
if (error.response && error.response.status === 500) {
router.push('/500')
}
return Promise.reject(error)
}
)
服务端渲染(SSR)处理
对于 Nuxt.js 项目,可以在 layouts/error.vue 中定义错误页面:
<template>
<div>
<h1 v-if="error.statusCode === 500">500 - 服务器错误</h1>
<button @click="$router.go(-1)">返回</button>
</div>
</template>
<script>
export default {
props: ['error']
}
</script>
错误边界组件(Vue 2.6+)
使用 Vue 的错误边界功能捕获组件树中的错误:
<template>
<error-boundary>
<component-that-may-error/>
<template #fallback>
<div>组件渲染出错,显示备用内容</div>
</template>
</error-boundary>
</template>
<script>
import { ErrorBoundary } from 'vue-error-boundary'
export default {
components: { ErrorBoundary }
}
</script>
实现时需注意错误处理的范围和粒度,避免过度捕获影响正常错误调试。生产环境应记录错误日志以便后续分析。







