javascript / intermediate
Snippet
Building Custom Error Class Hierarchies for Async Vue Handlers
Object-oriented error hierarchies inherit from JavaScript's native Error class. In asynchronous Vue actions, using instanceof checks on custom error subclasses lets you handle domain-specific exceptions, like form validation errors, distinctly from generic network failures.
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
26
27
28
29
class AppError extends Error {constructor(message, statusCode = 500) {super(message);this.name = this.constructor.name;this.statusCode = statusCode;}}class ValidationError extends AppError {constructor(message, fields = {}) {super(message, 422);this.fields = fields;}}export async function fetchUserData(userId, errorStateRef) {try {if (!userId) throw new ValidationError('User ID missing', { userId: 'Required' });const res = await fetch(`/api/users/${userId}`);if (!res.ok) throw new AppError('Server error', res.status);return await res.json();} catch (err) {if (err instanceof ValidationError) {errorStateRef.value = `Validation failed: ${JSON.stringify(err.fields)}`;} else {errorStateRef.value = 'An unexpected error occurred';}}}
vue
Breakdown
1
class AppError extends Error {
Creates a base custom error class with status code metadata.
2
class ValidationError extends AppError {
Inherits from base error to carry specific field-level validation payloads.
3
if (!userId) throw new ValidationError('User ID missing', { userId: 'Required' });
Instantiates and throws the specialized subclass for invalid parameters.
4
if (err instanceof ValidationError) {
Uses polymorphic type checks to branch handling logic specifically for validation issues.