javascript / expert
Snippet
Global Error Handling and Classification in Application Config
This snippet illustrates how custom class inheritance combined with Vue's application-wide errorHandler hook enables centralized error classification. Distinguishing custom ApplicationError domain exceptions from unhandled JavaScript runtime crashes simplifies logging and recovery.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import { createApp, ComponentPublicInstance } from 'vue';import App from './App.vue';class ApplicationError extends Error {constructor(message: string, public code: string) {super(message);this.name = 'ApplicationError';}}const app = createApp(App);app.config.errorHandler = (err: unknown,instance: ComponentPublicInstance | null,info: string) => {if (err instanceof ApplicationError) {console.warn(`Domain Error [${err.code}]: ${err.message} in hook (${info})`);} else if (err instanceof Error) {console.error(`Unhandled Runtime Exception: ${err.stack} at lifecycle (${info})`);} else {console.error('Unknown throw caught:', err, info);}};
vue
Breakdown
1
class ApplicationError extends Error {
Extends standard JS Error class to define custom error taxonomies with diagnostic error codes.
2
app.config.errorHandler = (err, instance, info) => {
Hooks into Vue's global error dispatcher to capture uncaught lifecycle exceptions application-wide.
3
if (err instanceof ApplicationError) {
Uses control flow type guards to differentiate domain-specific errors from generic JavaScript errors.
4
console.warn(`Domain Error [${err.code}]: ${err.message} in hook (${info})`);
Handles categorized domain errors gracefully with specialized logging strategies.
5
console.error(`Unhandled Runtime Exception: ${err.stack} at lifecycle (${info})`);
Extracts detailed call stack traces and Vue component lifecycle hook context for unexpected errors.