JavaScript Error Handling Cheat Sheet
Covers try/catch/finally, custom Error subclasses, handling errors in promises and async/await, and the ES2022 error cause chain.
1 PageIntermediateApr 5, 2026
try/catch/finally Basics
Core syntax for catching and cleaning up after errors.
javascript
try { const data = JSON.parse(input); // may throw SyntaxError process(data);} catch (err) { console.error('Failed:', err.message); // handle the error} finally { cleanup(); // always runs, even after return/throw}// Optional catch binding (ES2019) - omit the error variabletry { riskyOperation();} catch { console.log('Something went wrong');}
Custom Error Classes
Extend Error to create typed, catchable error subclasses.
javascript
class ValidationError extends Error { constructor(message, field) { super(message); this.name = 'ValidationError'; // shows up in stack traces this.field = field; }}function validate(age) { if (age < 0) throw new ValidationError('Age cannot be negative', 'age');}try { validate(-1);} catch (err) { if (err instanceof ValidationError) { console.log(`${err.field}: ${err.message}`); }}
Errors in Promises & async/await
Handle rejections in async functions, promise chains, and globally.
javascript
// async/await - wrap in try/catchasync function loadUser(id) { try { const res = await fetch(`/api/users/${id}`); if (!res.ok) throw new Error(`HTTP ${res.status}`); return await res.json(); } catch (err) { console.error('loadUser failed:', err); throw err; // re-throw so callers can react too }}// Promise chains - use .catch()fetchData() .then(process) .catch(err => console.error('Pipeline failed:', err));// Unhandled rejectionswindow.addEventListener('unhandledrejection', e => { console.error('Unhandled:', e.reason);});
Built-in Error Types & Properties
Standard error constructors and the fields available on any error.
- Error- Base error type; constructor accepts (message, options) where options.cause sets a chained cause
- TypeError- Thrown when a value is not of the expected type, e.g. calling a non-function
- RangeError- Thrown when a numeric value is outside its allowed range, e.g. invalid array length
- SyntaxError- Thrown when parsing invalid JS or JSON.parse fails
- ReferenceError- Thrown when referencing an undeclared variable
- err.message- Human-readable description of the error
- err.stack- Non-standard but widely supported stack trace string
- err.cause- ES2022 option for chaining the underlying cause: new Error('msg', { cause: original })
Error Cause Chaining (ES2022)
Preserve the original error when wrapping it in a higher-level one.
javascript
try { await connectToDb();} catch (dbErr) { throw new Error('Failed to start server', { cause: dbErr }); // preserves original error}// Later, when logging:catch (err) { console.error(err.message); console.error('Caused by:', err.cause);}
Pro Tip
Always throw Error objects (or subclasses), never plain strings or objects - only Error instances capture a stack trace, and tools like Sentry rely on err.stack to be useful.
Was this cheat sheet helpful?
Explore Topics
#JavaScriptErrorHandling#JavaScriptErrorHandlingCheatSheet#Programming#Intermediate#TryCatchFinallyBasics#CustomErrorClasses#Errors#Promises#Concurrency#ErrorHandling#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech
Professional Web Designing Services
- Responsive Websites
- E-commerce Solutions
- SEO Friendly Design
- Fast & Secure
- Support & Maintenance