Custom Errors in JavaScript

Create and use custom error classes

IntermediateError HandlingExample 2 of 10
custom-errors.js
1// Method 1: Custom error class
2class CustomError extends Error {
3 constructor(message, code) {
4 super(message);
5 this.name = 'CustomError';
6 this.code = code;
7 }
8}
9
10try {
11 throw new CustomError('Something went wrong', 'ERR001');
12} catch (error) {
13 console.error('Custom error:', error.message);
14 console.error('Error code:', error.code);
15}
16
17// Method 2: Multiple custom errors
18class ValidationError extends Error {
19 constructor(message, field) {
20 super(message);
21 this.name = 'ValidationError';
22 this.field = field;
23 }
24}
25
26class NotFoundError extends Error {
27 constructor(resource) {
28 super(`${resource} not found`);
29 this.name = 'NotFoundError';
30 this.resource = resource;
31 }
32}
33
34try {
35 throw new ValidationError('Invalid email', 'email');
36} catch (error) {
37 if (error instanceof ValidationError) {
38 console.error('Validation error:', error.message, 'Field:', error.field);
39 }
40}
41
42// Method 3: Error factory
43function createError(type, message, details = {}) {
44 const error = new Error(message);
45 error.name = type;
46 Object.assign(error, details);
47 return error;
48}
49
50try {
51 throw createError('DatabaseError', 'Connection failed', { host: 'localhost', port: 5432 });
52} catch (error) {
53 console.error('Error:', error.name, error.message, error.host);
54}
55
56// Method 4: Error with stack trace
57class DetailedError extends Error {
58 constructor(message, context = {}) {
59 super(message);
60 this.name = 'DetailedError';
61 this.context = context;
62 this.timestamp = new Date().toISOString();
63 }
64
65 toJSON() {
66 return {
67 name: this.name,
68 message: this.message,
69 context: this.context,
70 timestamp: this.timestamp,
71 stack: this.stack
72 };
73 }
74}
75
76const error = new DetailedError('Operation failed', { userId: 123, action: 'update' });
77console.log('Error JSON:', JSON.stringify(error, null, 2));

Output

Custom error: Something went wrong
Error code: ERR001
Validation error: Invalid email Field: email
Error: DatabaseError Connection failed localhost
Error JSON: {
  "name": "DetailedError",
  "message": "Operation failed",
  "context": { "userId": 123, "action": "update" },
  "timestamp": "2024-01-15T10:30:45.123Z",
  "stack": "..."
}

What's going on

Custom errors provide specific error types.

Custom Error Class

Extend Error
Add custom properties
Set error name
Include context

Error Types

ValidationError
NotFoundError
DatabaseError
Custom types

Error Factory

Create errors dynamically
Add context
Consistent format

Error Serialization

toJSON method
Include stack trace
Add metadata

Best Practices

Use specific error types
Include context
Add helpful messages
Serialize properly