Routing error handling improvement
Improvement of Route Error Handling
In Vue.js applications, route error handling is a key aspect of enhancing user experience. Traditional methods may rely solely on router.onError
to capture navigation errors, but modern Vue Router provides more granular control. Below, we elaborate step-by-step from error classification to specific implementation solutions.
Error Type Classification
Route errors are mainly divided into three categories:
- Navigation Guard Rejection: Actively interrupted via
next(false)
ornext(new Error())
- Component Loading Failure: Network errors during asynchronous route component loading
- Invalid Route Matching: Accessing undefined route paths
// Navigation guard example
router.beforeEach((to, from, next) => {
if (!userAuthenticated && to.meta.requiresAuth) {
next({ name: 'login' }) // Redirect
// or next(false) // Abort navigation
} else {
next()
}
})
Global Error Capture Solutions
Basic Error Capture
// Global error handler
router.onError((error) => {
console.error('Route error:', error)
// Optionally redirect to a unified error page
if (isNavigationFailure(error, NavigationFailureType.redirected)) {
showToast('Navigation was redirected')
}
})
Enhanced Error Handling
Combined with Vue's errorCaptured
lifecycle:
// In the root component
export default {
errorCaptured(err, vm, info) {
if (err instanceof NavigationFailure) {
this.$store.commit('ADD_ROUTE_ERROR', err)
return false // Prevent the error from propagating further
}
}
}
Asynchronous Component Loading Optimization
Handling dynamic import failures:
const UserDetails = () => ({
component: import('./UserDetails.vue'),
loading: LoadingComponent,
error: ErrorComponent,
delay: 200,
timeout: 3000
})
// Or using the new defineAsyncComponent
const AsyncComp = defineAsyncComponent({
loader: () => import('./Article.vue'),
onError(error, retry, fail) {
if (error.message.includes('timeout')) {
retry()
} else {
fail()
}
}
})
404 Route Handling Practice
Implementing an intelligent 404 page:
const routes = [
// ...other routes
{
path: '/:pathMatch(.*)*',
component: NotFound,
beforeEnter(to) {
// Analyze the path for intelligent redirection
const possibleRedirect = analyzePath(to.params.pathMatch)
if (possibleRedirect) {
return possibleRedirect
}
}
}
]
Error State Management
Incorporating route errors into Vuex/Pinia for unified management:
// Pinia store example
export const useErrorStore = defineStore('errors', {
state: () => ({
routeErrors: [],
lastError: null
}),
actions: {
addRouteError(error) {
this.routeErrors.push({
error,
timestamp: new Date(),
route: router.currentRoute.value
})
this.lastError = error
}
}
})
// Usage in route guards
router.onError((error) => {
useErrorStore().addRouteError(error)
})
Development Environment Debugging Enhancements
Leveraging Vue Devtools for extended route debugging:
if (process.env.NODE_ENV === 'development') {
router.afterEach((to, from, failure) => {
if (failure) {
console.group('[Route Error]')
console.log('Failure type:', failure.type)
console.log('Target route:', to)
console.log('Source route:', from)
console.groupEnd()
}
})
}
User Feedback Design
Providing friendly interaction when errors occur:
<template>
<div v-if="routeError">
<h3>Page Load Failed</h3>
<p>{{ errorMessage }}</p>
<button @click="retry">Retry</button>
<button @click="report">Report Issue</button>
</div>
</template>
<script>
export default {
data() {
return {
routeError: null
}
},
computed: {
errorMessage() {
if (!this.routeError) return ''
return this.routeError.isNetworkError
? 'Network connection error'
: 'Failed to load page resources'
}
},
methods: {
retry() {
this.$router.go()
},
report() {
// Send error report
}
}
}
</script>
Performance Monitoring Integration
Connecting route errors to performance monitoring systems:
import { trackError } from './monitoring'
router.onError((error) => {
trackError({
type: 'ROUTE_FAILURE',
error,
route: router.currentRoute.value,
timing: performance.now() - navigationStartTime
})
})
router.beforeEach(() => {
navigationStartTime = performance.now()
})
Testing Strategy Recommendations
Writing test cases for route errors:
import { mount } from '@vue/test-utils'
describe('Route Error Handling', () => {
it('should display 404 page when accessing an invalid route', async () => {
const wrapper = mount(App, {
global: {
plugins: [router]
}
})
await router.push('/invalid-route')
expect(wrapper.findComponent(NotFound).exists()).toBe(true)
})
it('should catch asynchronous component loading errors', async () => {
jest.spyOn(console, 'error').mockImplementation(() => {})
const error = new Error('Load failed')
importMock.mockRejectedValueOnce(error)
await router.push('/async-route')
await flushPromises()
expect(wrapper.findComponent(ErrorComponent).exists()).toBe(true)
})
})
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:路由过渡动画变化
下一篇:路由与Pinia集成