Back to KB
Difficulty
Intermediate
Read Time
5 min
Error Handling in JavaScript: The Complete Guide
By Codcompass TeamΒ·Β·5 min read
Stop your app from crashing. Handle errors like a pro.
The Basics
// try/catch/finally
try {
const data = JSON.parse(userInput);
console.log(data.name);
} catch (error) {
console.error('Failed to parse:', error.message);
} finally {
// Always runs β cleanup code here
console.log('Parse attempt finished');
}
// Throwing errors
throw new Error('Something went wrong');
throw new TypeError('Expected a string');
throw new RangeError('Index out of bounds');
throw new ValidationError('Invalid email'); // Custom!
Enter fullscreen mode Exit fullscreen mode
Custom Error Classes
class AppError extends Error {
constructor(message, statusCode = 500, code = 'INTERNAL_ERROR') {
super(message);
this.name = this.constructor.name;
this.statusCode = statusCode;
this.code = code;
this.timestamp = new Date().toISOString();
Error.captureStackTrace(this, this.constructor);
}
}
class NotFoundError extends AppError {
constructor(resource = 'Resource') {
super(`${resource} not found`, 404, 'NOT_FOUND');
}
}
class ValidationError extends AppError {
constructor(fields) {
super('Validation failed', 422, 'VALIDATION_ERROR');
this.fields = fields; // { field: ['error1', 'error2'] }
}
}
class RateLimitError extends AppError {
constructor(retryAfter = 60) {
super('Too many requests', 429, 'RATE_LIMITED');
this.retryAfter = retryAfter;
}
}
// Usage
try {
if (!user) throw new NotFoundError('User');
if (!isValidEmail(email)) throw new ValidationError({ email: ['Invalid format'] });
} catch (error) {
if (error instanceof NotFoundError) {
res.status(404).json({ error: error.message });
} else if (error instanceof ValidationError) {
res.status(422).json({ error: error.message, details: error.fields });
} else {
res.status(500).json({ error: 'Internal server error' });
}
}
Enter fullscreen mode Exit fullscreen mode
Async Error Handling
Pattern 1: try/catch with async/await
async function fetchUse
π Mid-Year Sale β Unlock Full Article
Base plan from just $4.99/mo or $49/yr
Sign in to read the full article and unlock all 635+ tutorials.
Sign In / Register β Start Free Trial7-day free trial Β· Cancel anytime Β· 30-day money-back
