What is Error Handling in JavaScript?
Error handling is the process of anticipating, detecting, and resolving programming, application, or communication errors. In JavaScript, error handling helps prevent your application from crashing and provides a better user experience by gracefully handling unexpected situations.
Try-Catch-Finally Block
Basic Syntax
try {
// Code that might throw an error
riskyOperation();
} catch (error) {
// Code to handle the error
console.error('An error occurred:', error.message);
} finally {
// Code that runs regardless of success or failure
console.log('Operation completed');
}
Example 1: Handling Division by Zero
function divideNumbers(a, b) {
try {
if (b === 0) {
throw new Error('Division by zero is not allowed');
}
return a / b;
} catch (error) {
console.error('Error:', error.message);
return null;
}
}
console.log(divideNumbers(10, 2)); // 5
console.log(divideNumbers(10, 0)); // Error message + null
Throw Statement
Custom Error Example
function validateEmail(email) {
try {
if (!email.includes('@')) {
throw new Error('Invalid email format');
}
if (!email.endsWith('.com') && !email.endsWith('.net')) {
throw new Error('Email must end with .com or .net');
}
return 'Email is valid';
} catch (error) {
return error.message;
}
}
console.log(validateEmail('test@example.com')); // Email is valid
console.log(validateEmail('test.example')); // Invalid email format
Error Types
Built-in Error Types
// TypeError
try {
null.function(); // Trying to call function on null
} catch (error) {
console.log('TypeError:', error.message);
}
// ReferenceError
try {
console.log(undefinedVariable); // Using undefined variable
} catch (error) {
console.log('ReferenceError:', error.message);
}
// SyntaxError (caught during parsing, not runtime)
try {
eval('const x = ;'); // Invalid syntax
} catch (error) {
console.log('SyntaxError:', error.message);
}
Custom Error Classes
Creating Custom Errors
class ValidationError extends Error {
constructor(message, field) {
super(message);
this.name = 'ValidationError';
this.field = field;
this.timestamp = new Date();
}
}
function validateUser(user) {
try {
if (!user.name) {
throw new ValidationError('Name is required', 'name');
}
if (!user.email) {
throw new ValidationError('Email is required', 'email');
}
if (user.age < 18) {
throw new ValidationError('Must be 18 or older', 'age');
}
return 'User is valid';
} catch (error) {
if (error instanceof ValidationError) {
console.error(`Validation failed for ${error.field}: ${error.message}`);
console.error(`Timestamp: ${error.timestamp}`);
} else {
console.error('Unknown error:', error.message);
}
return 'Validation failed';
}
}
const user = { name: 'John', email: 'john@example.com', age: 16 };
validateUser(user);
Promise Error Handling
Async/Await with Try-Catch
async function fetchUserData(userId) {
try {
const response = await fetch(`https://api.example.com/users/${userId}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error('Failed to fetch user data:', error.message);
throw error; // Re-throw to let caller handle it
}
}
// Using the async function
async function getUserProfile(userId) {
try {
const userData = await fetchUserData(userId);
console.log('User data:', userData);
} catch (error) {
console.error('Could not get user profile:', error.message);
}
}
Promise .catch() Method
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
console.log('Data:', data);
})
.catch(error => {
console.error('Fetch error:', error.message);
})
.finally(() => {
console.log('Fetch operation completed');
});
Window Error Event Handling
Global Error Handler
// Handle uncaught errors globally
window.addEventListener('error', function(event) {
console.error('Global error caught:', event.error.message);
// You can send this to error tracking service
// sendErrorToServer(event.error);
// Prevent default browser error handling
event.preventDefault();
});
// Handle unhandled promise rejections
window.addEventListener('unhandledrejection', function(event) {
console.error('Unhandled promise rejection:', event.reason);
event.preventDefault();
});
Practical Example: Form Validation
class FormValidator {
static validateForm(formData) {
const errors = [];
try {
// Validate name
if (!formData.name || formData.name.trim().length < 2) {
throw new ValidationError('Name must be at least 2 characters', 'name');
}
// Validate email
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(formData.email)) {
throw new ValidationError('Invalid email format', 'email');
}
// Validate password
if (!formData.password || formData.password.length < 8) {
throw new ValidationError('Password must be at least 8 characters', 'password');
}
return { success: true, message: 'Form is valid' };
} catch (error) {
if (error instanceof ValidationError) {
return {
success: false,
message: error.message,
field: error.field
};
}
return {
success: false,
message: 'An unexpected error occurred'
};
}
}
}
// Usage
const formData = { name: 'J', email: 'invalid', password: '123' };
const result = FormValidator.validateForm(formData);
if (!result.success) {
console.error(`Error in ${result.field}: ${result.message}`);
} else {
console.log('Form submitted successfully');
}
Best Practices
- Be specific with error types: Use custom error classes for different error scenarios
- Don't swallow errors: Always handle or re-throw errors appropriately
- Provide meaningful error messages: Help with debugging and user communication
- Use finally for cleanup: Ensure resources are released regardless of success/failure
- Log errors appropriately: Use different log levels for different error types
Error handling is crucial for building robust, production-ready JavaScript applications that can gracefully handle unexpected situations and provide good user experiences.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.