Suggest an editImprove this articleRefine the answer for “Errors and their handling”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)**Error handling in JavaScript** relies on `try...catch...finally` and `throw` for synchronous code, and on `try...catch` around `async/await` or `.catch()` for promises in asynchronous code. **Key point:** global handlers (`window.onerror`, `process.on('uncaughtException')`) are a safety net, not a replacement for local handling.Shown above the full answer for quick recall.Answer (EN)Image## 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.For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.