Designing Vue 3 error handling plugin
The plan captures component errors, promise rejections, and API errors (via axios or fetch wrapping), deduplicates repeated errors within 1 second, and reports them through a customizable logging service. Next, I'll implement the plugin code with options for throttle timing, axios instance, fetch wrapping, and a default console logger.
Below is a minimal, framework‑agnostic Vue 3 plugin that installs a global error handler (app.config.errorHandler), captures unhandled promise rejections, and optionally intercepts API errors (via axios or a fetch wrapper). It also deduplicates “similar” errors within a configurable window (default: 1 s) to prevent flooding a logging service.
// error-plugin.ts
import type { App, Plugin } from 'vue'
import type { AxiosInstance } from 'axios'
type ErrorType = 'component' | 'promise' | 'api'
type ErrorPayload = {
type: ErrorType
message: string
stack?: string
info?: any
component?: string
url?: string
time: number
extra?: any
}
type ErrorPluginOptions = {
/**
* Function that will receive the normalized error payload.
* Replace with your API call to a logging service.
*/
logService?: (payload: ErrorPayload) => void | Promise<void>
/**
* Time window in ms to deduplicate identical errors
*/
throttleMs?: number
/**
* Optional axios instance to intercept API errors
*/
axiosInstance?: AxiosInstance
/**
* If true, wrap window.fetch to capture API errors
*/
wrapFetch?: boolean
}
/**
* Create a Vue plugin that installs global error capture + throttling
*/
export function createErrorPlugin (options: ErrorPluginOptions = {}): Plugin {
const {
logService = (payload) => console.error('Logged error:', payload),
throttleMs = 1000,
axiosInstance,
wrapFetch = false
} = options
// key => last timestamp sent
const cache = new Map<string, number>()
const buildKey = (payload: ErrorPayload) =>
`${payload.type}|${payload.message}|${payload.stack ?? ''}`
const shouldThrottle = (payload: ErrorPayload) => {
const now = Date.now()
const key = buildKey(payload)
const last = cache.get(key) ?? 0
if (now - last < throttleMs) return true
cache.set(key, now)
return false
}
const report = (payload: ErrorPayload) => {
if (!shouldThrottle(payload)) {
logService(payload)
}
}
const plugin: Plugin = {
install (app: App) {
// --- 1) Component error handler ---
const previousHandler = app.config.errorHandler
app.config.errorHandler = (err, instance, info) => {
report({
type: 'component',
message: err?.message || String(err),
stack: err?.stack,
info,
component: instance?.type?.name || instance?.type?.__file,
time: Date.now()
})
// call existing handler if defined
if (previousHandler) previousHandler(err, instance, info)
}
// --- 2) Unhandled promise rejections ---
window.addEventListener('unhandledrejection', (event) => {
report({
type: 'promise',
message: event.reason?.message || String(event.reason),
stack: event.reason?.stack,
time: Date.now()
})
})
// --- 3) API errors: axios interceptors ---
if (axiosInstance) {
axiosInstance.interceptors.response.use(
(response) => response,
(error) => {
report({
type: 'api',
message: error?.message || 'Axios error',
stack: error?.stack,
info: error?.response?.data,
url: error?.config?.url,
time: Date.now()
})
return Promise.reject(error)
}
)
}
// --- 4) API errors: fetch wrapper ---
if (wrapFetch && typeof window !== 'undefined' && 'fetch' in window) {
const originalFetch = window.fetch.bind(window)
window.fetch = async (...args: Parameters<typeof fetch>) => {
try {
const res = await originalFetch(...args)
if (!res.ok) {
throw new Error(`Fetch error ${res.status} ${res.statusText} at ${args[0]}`)
}
return res
} catch (err: any) {
report({
type: 'api',
message: err?.message || 'Fetch error',
stack: err?.stack,
url: String(args[0]),
time: Date.now()
})
throw err
}
}
}
}
}
return plugin
}
Usage
// main.ts
import { createApp } from 'vue'
import App from './App.vue'
import axios from 'axios'
import { createErrorPlugin } from './error-plugin'
// Example: your logging service endpoint
async function sendToLoggingService(payload: any) {
await fetch('/api/log-error', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
})
}
const app = createApp(App)
app.use(createErrorPlugin({
logService: sendToLoggingService, // or omit to just console.error
throttleMs: 1000,
axiosInstance: axios, // if you want to intercept axios API errors
wrapFetch: true // if you want to intercept fetch API errors
}))
app.mount('#app')
Notes / Extensions
- Adjust
buildKey to change what constitutes “similar” errors (e.g., include URL, component name, HTTP status).
- Replace
logService with your real logging endpoint or a queueing mechanism.
- Keep or remove
event.preventDefault() in unhandledrejection if your app needs to suppress default browser handling.