Error Handling & Debugging
try / catch / finally
try {
const data = JSON.parse(invalidJSON);
} catch (err) {
if (err instanceof SyntaxError) {
console.error('Invalid JSON:', err.message);
} else {
throw err; // re-throw unexpected errors
}
} finally {
console.log('Always runs');
}
Custom Error Classes
class ValidationError extends Error {
constructor(message, field) {
super(message);
this.name = 'ValidationError';
this.field = field;
}
}
try {
throw new ValidationError('Invalid email', 'email');
} catch (err) {
if (err instanceof ValidationError) {
console.log(err.field); // 'email'
}
}
Async Error Handling
// Promises
fetch('/api/data')
.then(res => res.json())
.catch(err => console.error('Fetch failed:', err));
// Async/Await
async function fetchData() {
try {
const res = await fetch('/api/data');
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return await res.json();
} catch (err) {
console.error(err);
}
}