Errors and their handling
Basic handling: try...catch...finally and throw
javascript
try {
risky(); // code that might fail
} catch (err) {
console.error(err.message); // handling/logging
} finally {
cleanup(); // always runs (even on error)
}Raising an error:
javascript
if (!user) {
throw new Error('User not found');
}Custom errors
javascript
class ValidationError extends Error {
constructor(message, cause) {
super(message, { cause }); // Node 16+/modern browsers: err.cause
this.name = 'ValidationError';
}
}
throw new ValidationError('Invalid email');2) Asynchronous code
a) async/await + try...catch
javascript
async function load() {
try {
const res = await fetch('/api/data');
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return await res.json();
} catch (err) {
// handling/retry/notification
console.error('Load failed:', err);
return null; // or rethrow: throw err
}
}b) Promises: .catch()
javascript
fetch('/api/data')
.then(r => r.json())
.catch(err => console.error('Request failed', err));c) Parallel operations without failing the whole batch
javascript
const results = await Promise.allSettled(urls.map(u => fetch(u)));
for (const r of results) {
if (r.status === 'fulfilled') console.log('OK', r.value);
else console.warn('Failed', r.reason);
}3) Global interceptors (the last line of defense)
Browser
javascript
// synchronous/uncaught exceptions
window.addEventListener('error', (event) => {
console.error('Uncaught error:', event.error, event.message, event.filename, event.lineno);
});
// uncaught promise rejections
window.addEventListener('unhandledrejection', (event) => {
console.error('Unhandled rejection:', event.reason);
});Node.js
javascript
process.on('uncaughtException', (err) => {
console.error('Uncaught Exception', err);
// logging + a graceful process shutdown
process.exit(1);
});
process.on('unhandledRejection', (reason) => {
console.error('Unhandled Rejection', reason);
// decide: log and shut down/continue per the app's policy
});Global handlers are a safety net, not a replacement for local handling.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.