Browser APIs and StorageLesson 8.1
Error Handling in JavaScript
try/catch/finally, Error object, custom errors, throwing errors, error types, defensive programming
Error Handling in JavaScript
Errors are inevitable in any real application. Users enter unexpected input, network requests fail, APIs return unexpected data. Robust JavaScript code anticipates these failures and handles them gracefully, providing useful feedback instead of crashing silently or with confusing messages.
try / catch / finally
function parseJSON(jsonString) {
try {
const data = JSON.parse(jsonString);
return data;
} catch (error) {
console.error('Invalid JSON:', error.message);
return null;
} finally {
console.log('parseJSON completed');
}
}
console.log(parseJSON('{"name":"Alice"}')); // { name: 'Alice' }
console.log(parseJSON('invalid json')); // nullThe Error Object
try {
null.property; // TypeError
} catch (error) {
console.log(error.name); // 'TypeError'
console.log(error.message); // "Cannot read properties of null"
console.log(error.stack); // full stack trace
}Throwing Custom Errors
class ValidationError extends Error {
constructor(field, message) {
super(message);
this.name = 'ValidationError';
this.field = field;
}
}
function validateAge(age) {
if (typeof age !== 'number') {
throw new ValidationError('age', 'Age must be a number');
}
if (age < 0 || age > 150) {
throw new ValidationError('age', 'Age must be between 0 and 150');
}
return true;
}
try {
validateAge(-5);
} catch (error) {
if (error instanceof ValidationError) {
console.error(`Validation failed on field '${error.field}': ${error.message}`);
} else {
throw error; // re-throw unexpected errors
}
}