Custom Errors
Create and use custom error classes
JavaScript Custom Errors Program
This program helps you to learn the fundamental structure and syntax of JavaScript programming.
// 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));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": "..."
}Understanding Custom Errors
Custom errors provide specific error types.
Custom Error Class
Error Types
Error Factory
Error Serialization
Best Practices
Let us now understand every line and the components of the above program.
Note: To write and run JavaScript programs, you need to set up the local environment on your computer. Refer to the complete article Setting up JavaScript Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your JavaScript programs.
Practical Learning Notes for Custom Errors
This JavaScript program is part of the "Error Handling" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.
A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.
For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.