Custom Errors

Create and use custom error classes

JavaScriptIntermediate
JavaScript
// Method 1: Custom error class
class CustomError extends Error {
    constructor(message, code) {
        super(message);
        this.name = 'CustomError';
        this.code = code;
    }
}

try {
    throw new CustomError('Something went wrong', 'ERR001');
} catch (error) {
    console.error('Custom error:', error.message);
    console.error('Error code:', error.code);
}

// Method 2: Multiple custom errors
class ValidationError extends Error {
    constructor(message, field) {
        super(message);
        this.name = 'ValidationError';
        this.field = field;
    }
}

class NotFoundError extends Error {
    constructor(resource) {
        super(`${resource} not found`);
        this.name = 'NotFoundError';
        this.resource = resource;
    }
}

try {
    throw new ValidationError('Invalid email', 'email');
} catch (error) {
    if (error instanceof ValidationError) {
        console.error('Validation error:', error.message, 'Field:', error.field);
    }
}

// Method 3: Error factory
function createError(type, message, details = {}) {
    const error = new Error(message);
    error.name = type;
    Object.assign(error, details);
    return error;
}

try {
    throw createError('DatabaseError', 'Connection failed', { host: 'localhost', port: 5432 });
} catch (error) {
    console.error('Error:', error.name, error.message, error.host);
}

// Method 4: Error with stack trace
class DetailedError extends Error {
    constructor(message, context = {}) {
        super(message);
        this.name = 'DetailedError';
        this.context = context;
        this.timestamp = new Date().toISOString();
    }
    
    toJSON() {
        return {
            name: this.name,
            message: this.message,
            context: this.context,
            timestamp: this.timestamp,
            stack: this.stack
        };
    }
}

const error = new DetailedError('Operation failed', { userId: 123, action: 'update' });
console.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": "..."
}

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