Create a Vue.js plugin for global error handling using app.config.errorHandler. Capture…
- User
Create a Vue.js plugin for global error handling using app.config.errorHandler. Capture component errors, promise rejections, and API errors. Deduplicate similar errors within 1 second before sending to a logging service to prevent flooding.
Assistant
This is a comprehensive request for a Vue.js error handling plugin. Let me create a well-structured solution that includes:
- A Vue.js plugin that sets up error handling
- Global error handler using app.config.errorHandler
- Promise rejection handling
- API error handling (likely via HTTP interceptors like Axios)
- Error deduplication within 1-second window
- Integration with a logging service
I'll provide:
- The main plugin file
- Error handler utility
- Error deduplication service
- Example logging service
- Integration with Axios
- Usage examples
- TypeScript support (optional but good to include)
- Configuration options
Let me structure this comprehensively:
// errorPlugin.ts // src/plugins/errorPlugin.ts or similar This should include: - Error tracking - Deduplication logic - Error classification (component, promise, API) - Service integration - ConfigurationI'll provide a complete, production-ready solution with good practices.
Vue.js Global Error Handling Plugin
I'll create a comprehensive error handling plugin with deduplication, classification, and logging integration.
1. Core Error Handler Plugin
// src/plugins/errorHandler/plugin.ts import { App, ComponentCustomProperties } from 'vue' import ErrorTracker from './tracker' import { ErrorConfig, ErrorLevel } from './types' let errorTracker: ErrorTracker declare global { interface Window { errorTracker?: ErrorTracker } } const defaultConfig: ErrorConfig = { deduplicationWindow: 1000, // 1 second enableLogging: true, enableConsole: true, logService: null, environment: process.env.NODE_ENV, maxErrorQueueSize: 100, apiErrorThreshold: 5, // Alert after N API errors } export function createErrorHandler(config: Partial<ErrorConfig> = {}) { return { install: (app: App, pluginConfig: Partial<ErrorConfig> = {}) => { const finalConfig = { ...defaultConfig, ...config, ...pluginConfig } errorTracker = new ErrorTracker(finalConfig) // Make available globally window.errorTracker = errorTracker // Vue component errors app.config.errorHandler = (err, instance, info) => { errorTracker.captureError({ error: err, type: 'component', componentName: instance?.$options.name || 'Unknown', lifecycleHook: info, timestamp: Date.now(), }) } // Promise rejections window.addEventListener('unhandledrejection', (event) => { errorTracker.captureError({ error: event.reason, type: 'promise', timestamp: Date.now(), }) }) // Global runtime errors window.addEventListener('error', (event) => { errorTracker.captureError({ error: event.error, type: 'runtime', message: event.message, filename: event.filename, lineno: event.lineno, colno: event.colno, timestamp: Date.now(), }) }) // Global component property for easy access app.config.globalProperties.$errorHandler = errorTracker }, } } export default createErrorHandler()2. Error Tracker with Deduplication
// src/plugins/errorHandler/tracker.ts import { CapturedError, ErrorConfig, ErrorLevel, ProcessedError } from './types' import { deduplicateError } from './deduplicator' import { classifyError } from './classifier' class ErrorTracker { private config: ErrorConfig private errorQueue: ProcessedError[] = [] private recentErrors: Map<string, number> = new Map() private errorStats: Map<string, number> = new Map() private batchTimer: NodeJS.Timeout | null = null constructor(config: ErrorConfig) { this.config = config } captureError(error: CapturedError): void { const processedError = this.processError(error) // Check for duplicate if (!deduplicateError(processedError, this.recentErrors, this.config.deduplicationWindow)) { return } // Track error statistics this.trackErrorStats(processedError) // Add to queue this.addToQueue(processedError) // Log locally if enabled if (this.config.enableConsole) { this.logToConsole(processedError) } // Schedule batch send this.scheduleBatchSend() } private processError(error: CapturedError): ProcessedError { const errorObj = this.normalizeError(error.error) const level = classifyError(error.type, errorObj) return { ...error, id: this.generateErrorId(), level, errorMessage: errorObj.message, errorStack: errorObj.stack, userAgent: navigator.userAgent, url: window.location.href, timestamp: error.timestamp || Date.now(), } } private normalizeError(err: any): { message: string; stack?: string } { if (err instanceof Error) { return { message: err.message, stack: err.stack, } } if (typeof err === 'string') { return { message: err } } if (typeof err === 'object' && err !== null) { return { message: err.message || JSON.stringify(err), stack: err.stack, } } return { message: String(err) } } private trackErrorStats(error: ProcessedError): void { const key = `${error.type}:${error.errorMessage}` this.errorStats.set(key, (this.errorStats.get(key) || 0) + 1) // Alert on API error threshold if (error.type === 'api' && this.errorStats.get(key)! >= this.config.apiErrorThreshold) { console.warn(`⚠️ High frequency API error detected: ${key}`) } } private addToQueue(error: ProcessedError): void { this.errorQueue.push(error) if (this.errorQueue.length > this.config.maxErrorQueueSize) { this.errorQueue.shift() } } private generateErrorId(): string { return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}` } private scheduleBatchSend(): void { if (this.batchTimer) { return } this.batchTimer = setTimeout(() => { this.flushErrors() this.batchTimer = null }, 500) // Send batch after 500ms } private async flushErrors(): Promise<void> { if (this.errorQueue.length === 0 || !this.config.enableLogging) { return } const errorsToSend = [...this.errorQueue] this.errorQueue = [] try { if (this.config.logService) { await this.config.logService.sendErrors(errorsToSend) } } catch (err) { console.error('Failed to send errors to logging service:', err) // Re-add errors to queue if send failed this.errorQueue.unshift(...errorsToSend) } } private logToConsole(error: ProcessedError): void { const style = this.getConsoleStyle(error.level) console.group(`%c[${error.level.toUpperCase()}] ${error.type.toUpperCase()} Error`, style) console.log('Message:', error.errorMessage) console.log('Component:', error.componentName || 'N/A') console.log('URL:', error.url) console.log('Timestamp:', new Date(error.timestamp).toISOString()) if (error.errorStack) { console.log('Stack:', error.errorStack) } console.table(this.getErrorContext(error)) console.groupEnd() } private getConsoleStyle(level: ErrorLevel): string { const styles = { critical: 'background: #d32f2f; color: white; padding: 2px 6px; border-radius: 3px; font-weight: bold;', error: 'background: #f57c00; color: white; padding: 2px 6px; border-radius: 3px; font-weight: bold;', warning: 'background: #fbc02d; color: black; padding: 2px 6px; border-radius: 3px; font-weight: bold;', info: 'background: #1976d2; color: white; padding: 2px 6px; border-radius: 3px; font-weight: bold;', } return styles[level] } private getErrorContext(error: ProcessedError): Record<string, any> { return { Type: error.type, Level: error.level, Component: error.componentName || 'N/A', 'API Endpoint': (error as any).endpoint || 'N/A', 'HTTP Status': (error as any).status || 'N/A', } } // Public methods getErrors(): ProcessedError[] { return [...this.errorQueue] } getErrorStats(): Record<string, number> { return Object.fromEntries(this.errorStats) } clearErrors(): void { this.errorQueue = [] this.errorStats.clear() } async captureAPIError( endpoint: string, status: number, message: string, response?: any ): Promise<void> { this.captureError({ error: { message: `API Error: ${message}`, endpoint, status, response, } as any, type: 'api', timestamp: Date.now(), }) } } export default ErrorTracker3. Error Deduplicator
// src/plugins/errorHandler/deduplicator.ts import { ProcessedError } from './types' export function deduplicateError( error: ProcessedError, recentErrors: Map<string, number>, deduplicationWindow: number ): boolean { const errorHash = generateErrorHash(error) const now = Date.now() // Check if we've seen this error recently const lastOccurrence = recentErrors.get(errorHash) if (lastOccurrence && now - lastOccurrence < deduplicationWindow) { // Duplicate found within deduplication window return false } // New error or enough time has passed recentErrors.set(errorHash, now) // Cleanup old entries cleanupOldErrors(recentErrors, deduplicationWindow) return true } export function generateErrorHash(error: ProcessedError): string { const key = [ error.type, error.level, error.errorMessage, error.componentName, (error as any).endpoint, // for API errors ] .filter(Boolean) .join('|') return hashString(key) } function hashString(str: string): string { let hash = 0 for (let i = 0; i < str.length; i++) { const char = str.charCodeAt(i) hash = (hash << 5) - hash + char hash = hash & hash // Convert to 32bit integer } return String(hash) } function cleanupOldErrors( recentErrors: Map<string, number>, deduplicationWindow: number ): void { const now = Date.now() const keysToDelete: string[] = [] recentErrors.forEach((timestamp, key) => { if (now - timestamp > deduplicationWindow) { keysToDelete.push(key) } }) keysToDelete.forEach((key) => recentErrors.delete(key)) }4. Error Classifier
// src/plugins/errorHandler/classifier.ts import { ErrorLevel } from './types' export function classifyError(type: string, error: any): ErrorLevel { // API errors if (type === 'api') { const status = error.status || error.statusCode if (status >= 500) return 'critical' if (status >= 400) return 'error' return 'warning' } // Promise rejections if (type === 'promise') { if (error.message?.includes('timeout')) return 'warning' if (error.message?.includes('abort')) return 'warning' return 'error' } // Component errors if (type === 'component') { if (error.message?.includes('lifecycle')) return 'warning' if (error.message?.includes('render')) return 'error' return 'error' } // Runtime errors if (type === 'runtime') { if (error.message?.includes('warning')) return 'warning' if (error.message?.includes('syntax')) return 'critical' return 'error' } return 'info' }5. Type Definitions
// src/plugins/errorHandler/types.ts export type ErrorType = 'component' | 'promise' | 'api' | 'runtime' export type ErrorLevel = 'critical' | 'error' | 'warning' | 'info' export interface CapturedError { error: any type: ErrorType componentName?: string lifecycleHook?: string endpoint?: string status?: number message?: string filename?: string lineno?: number colno?: number timestamp?: number } export interface ProcessedError extends CapturedError { id: string level: ErrorLevel errorMessage: string errorStack?: string userAgent: string url: string } export interface LogService { sendErrors(errors: ProcessedError[]): Promise<void> } export interface ErrorConfig { deduplicationWindow: number enableLogging: boolean enableConsole: boolean logService: LogService | null environment: string maxErrorQueueSize: number apiErrorThreshold: number } declare global { interface ComponentCustomProperties { $errorHandler: any } }6. Axios Integration
// src/plugins/errorHandler/axios-interceptor.ts import { AxiosError, AxiosInstance } from 'axios' import ErrorTracker from './tracker' export function setupAxiosErrorHandling( axios: AxiosInstance, errorTracker: ErrorTracker ): void { axios.interceptors.response.use( (response) => response, (error: AxiosError) => { const status = error.response?.status || 0 const endpoint = error.config?.url || 'Unknown' const message = error.message || 'API Request Failed' // Capture the error errorTracker.captureAPIError( endpoint, status, message, error.response?.data ) // Return the error to allow further handling return Promise.reject(error) } ) }7. Example Logging Service
// src/services/logging.service.ts import { ProcessedError, LogService } from '@/plugins/errorHandler/types' class LoggingService implements LogService { private apiUrl: string private apiKey: string private retryAttempts: number = 3 constructor(apiUrl: string, apiKey: string) { this.apiUrl = apiUrl this.apiKey = apiKey } async sendErrors(errors: ProcessedError[]): Promise<void> { const payload = { errors: errors.map((error) => ({ id: error.id, type: error.type, level: error.level, message: error.errorMessage, stack: error.errorStack, component: error.componentName, url: error.url, endpoint: (error as any).endpoint, status: (error as any).status, userAgent: error.userAgent, timestamp: error.timestamp, })), timestamp: new Date().toISOString(), environment: process.env.NODE_ENV, } await this.sendWithRetry(payload, 0) } private async sendWithRetry(payload: any, attempt: number): Promise<void> { try { const response = await fetch(this.apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.apiKey}`, }, body: JSON.stringify(payload), }) if (!response.ok) { throw new Error(`HTTP ${response.status}: ${response.statusText}`) } console.log(`✅ Sent ${payload.errors.length} errors to logging service`) } catch (error) { if (attempt < this.retryAttempts) { const delay = Math.pow(2, attempt) * 1000 console.warn( `Failed to send errors (attempt ${attempt + 1}/${this.retryAttempts}), retrying in ${delay}ms` ) await new Promise((resolve) => setTimeout(resolve, delay)) return this.sendWithRetry(payload, attempt + 1) } console.error('Failed to send errors after all retries:', error) throw error } } } export default LoggingService8. Setup in main.ts
// src/main.ts import { createApp } from 'vue' import axios from 'axios' import App from './App.vue' import router from './router' import { createErrorHandler } from '@/plugins/errorHandler/plugin' import { setupAxiosErrorHandling } from '@/plugins/errorHandler/axios-interceptor' import LoggingService from '@/services/logging.service' const app = createApp(App) // Setup logging service const loggingService = new LoggingService( process.env.VUE_APP_LOG_API_URL || 'https://api.example.com/logs', process.env.VUE_APP_LOG_API_KEY || '' ) // Setup error handler plugin app.use( createErrorHandler({ enableLogging: true, enableConsole: true, deduplicationWindow: 1000, logService: loggingService, environment: process.env.NODE_ENV, maxErrorQueueSize: 100, apiErrorThreshold: 5, }) ) // Setup Axios error handling setupAxiosErrorHandling(axios, window.errorTracker!) app.use(router) app.mount('#app')9. Usage Examples
// src/components/ExampleComponent.vue <script setup lang="ts"> import { ref, inject } from 'vue' import type ErrorTracker from '@/plugins/errorHandler/tracker' const errorTracker = inject<ErrorTracker>('$errorHandler') const count = ref(0) // Example 1: Throw component error const throwError = () => { throw new Error('This is a component error') } // Example 2: Promise rejection const promiseRejection = () => { Promise.reject(new Error('Unhandled promise rejection')) } // Example 3: API error const apiError = async () => { try { const response = await fetch('https://api.example.com/invalid') if (!response.ok) { throw new Error(`HTTP ${response.status}`) } } catch (error) { errorTracker?.captureError({ error, type: 'api', timestamp: Date.now(), }) } } // Example 4: Trigger unhandled rejection const triggerUnhandled = async () => { new Promise(() => { throw new Error('Unhandled in promise') }) } // Get error statistics const getStats = () => { console.log('Error Stats:', errorTracker?.getErrorStats()) console.log('Recent Errors:', errorTracker?.getErrors()) } </script> <template> <div class="error-test"> <h2>Error Handling Examples</h2> <div class="button-group"> <button @click="throwError" class="btn btn-danger"> Throw Component Error </button> <button @click="promiseRejection" class="btn btn-warning"> Promise Rejection </button> <button @click="apiError" class="btn btn-info"> API Error </button> <button @click="triggerUnhandled" class="btn btn-secondary"> Unhandled Promise </button> <button @click="getStats" class="btn btn-primary"> Show Stats </button> </div> </div> </template> <style scoped> .error-test { padding: 20px; border: 1px solid #ddd; border-radius: 4px; } .button-group { display: flex; gap: 10px; flex-wrap: wrap; margin-top: 16px; } .btn { padding: 8px 16px; border: none; border-radius: 4px; cursor: pointer; font-weight: 500; } .btn-primary { background: #1976d2; color: white; } .btn-danger { background: #d32f2f; color: white; } .btn-warning { background: #fbc02d; color: black; } .btn-info { background: #0097a7; color: white; } .btn-secondary { background: #757575; color: white; } .btn:hover { opacity: 0.8; } </style>10. Error Dashboard Component (Optional)
// src/components/ErrorDashboard.vue <script setup lang="ts"> import { ref, computed, inject } from 'vue' import type ErrorTracker from '@/plugins/errorHandler/tracker' const errorTracker = inject<ErrorTracker>('$errorHandler') const refreshInterval = ref(2000) const errors = computed(() => errorTracker?.getErrors() || []) const stats = computed(() => errorTracker?.getErrorStats() || {}) const levelColor = (level: string) => { const colors = { critical: '#d32f2f', error: '#f57c00', warning: '#fbc02d', info: '#1976d2', } return colors[level as keyof typeof colors] || '#999' } const clearErrors = () => { errorTracker?.clearErrors() } </script> <template> <div class="error-dashboard"> <div class="header"> <h2>Error Dashboard</h2> <button @click="clearErrors" class="clear-btn">Clear Errors</button> </div> <div class="stats-grid"> <div v-for="(count, type) in stats" :key="type" class="stat-card"> <div class="stat-label">{{ type }}</div> <div class="stat-value">{{ count }}</div> </div> </div> <div class="errors-list"> <div v-if="errors.length === 0" class="no-errors"> No errors captured </div> <div v-for="error in errors" :key="error.id" class="error-item"> <div class="error-header"> <span class="level" :style="{ backgroundColor: levelColor(error.level) }"> {{ error.level.toUpperCase() }} </span> <span class="type">{{ error.type.toUpperCase() }}</span> <span class="time">{{ new Date(error.timestamp).toLocaleTimeString() }}</span> </div> <div class="error-message">{{ error.errorMessage }}</div> <div v-if="error.componentName" class="error-component"> Component: {{ error.componentName }} </div> <details v-if="error.errorStack" class="stack-trace"> <summary>Stack Trace</summary> <pre>{{ error.errorStack }}</pre> </details> </div> </div> </div> </template> <style scoped> .error-dashboard { max-width: 1200px; margin: 0 auto; padding: 20px; background: #f5f5f5; border-radius: 8px; } .header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; } .clear-btn { padding: 8px 16px; background: #d32f2f; color: white; border: none; border-radius: 4px; cursor: pointer; } .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 16px; margin-bottom: 24px; } .stat-card { background: white; padding: 16px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); } .stat-label { font-size: 12px; color: #666; text-transform: uppercase; margin-bottom: 8px; } .stat-value { font-size: 24px; font-weight: bold; color: #333; } .errors-list { background: white; border-radius: 8px; overflow: hidden; } .no-errors { padding: 40px; text-align: center; color: #999; } .error-item { padding: 16px; border-bottom: 1px solid #eee; } .error-item:last-child { border-bottom: none; } .error-header { display: flex; gap: 12px; align-items: center; margin-bottom: 8px; } .level { padding: 2px 8px; border-radius: 4px; color: white; font-size: 12px; font-weight: bold; } .type { color: #666; font-size: 12px; text-transform: uppercase; font-weight: 600; } .time { margin-left: auto; color: #999; font-size: 12px; } .error-message { color: #333; margin-bottom: 8px; font-weight: 500; } .error-component { color: #666; font-size: 12px; margin-bottom: 8px; } .stack-trace { margin-top: 8px; cursor: pointer; } .stack-trace summary { color: #1976d2; font-size: 12px; padding: 4px; } .stack-trace pre { background: #f5f5f5; padding: 12px; border-radius: 4px; overflow-x: auto; font-size: 11px; margin-top: 8px; } </style>11. Environment Configuration
# .env.example VUE_APP_LOG_API_URL=https://api.example.com/logs VUE_APP_LOG_API_KEY=your-api-key-here NODE_ENV=development12. Complete Example Structure
src/ ├── plugins/ │ └── errorHandler/ │ ├── plugin.ts │ ├── tracker.ts │ ├── deduplicator.ts │ ├── classifier.ts │ ├── types.ts │ └── axios-interceptor.ts ├── services/ │ └── logging.service.ts ├── components/ │ ├── ExampleComponent.vue │ └── ErrorDashboard.vue └── main.tsKey Features
✅ Component Error Capture - Catches Vue lifecycle errors
✅ Promise Rejection Handling - Unhandled promise rejections
✅ API Error Tracking - Axios integration
✅ Error Deduplication - Prevents error flooding within 1-second window
✅ Error Classification - Categorizes by type and level
✅ Batch Sending - Groups errors for efficient logging
✅ Error Statistics - Tracks error frequency
✅ Console Logging - Development-friendly output
✅ Retry Logic - Handles logging service failures
✅ Type Safe - Full TypeScript supportThis solution is production-ready and handles all major error scenarios!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.