JavaScript Error Handling
Handle problems safely in JavaScript. Use try, catch and finally, custom errors, async errors, retries, logging and recovery, with real output for each program.
10 programs · open one, then the next
Start with Try-Catch-Finally- 01Try-Catch-FinallyBeginnerLearn try, catch and finally in JavaScript: catch JSON errors, nest blocks, read error name and stack, and handle async errors. Explanation and output.Open example →js// Method 1: Basic try-catch try { const result = 10 / 0; console.log('Result:', result);
- 02Custom ErrorsIntermediateCreate custom errors in JavaScript with classes that extend Error, extra fields like code, an error factory and toJSON for logging. Explanation and output.Open example →js// Method 1: Custom error class class CustomError extends Error { constructor(message, code) { super(message);
- 03Error PropagationIntermediateSee how errors move up through function calls in JavaScript: re-throw, wrap an error with context, chain causes and log in one place. Explanation and output.Open example →js// Method 1: Re-throw error function level1() { try { level2();
- 04Async Error HandlingIntermediateHandle async errors in JavaScript with try/catch and await, .catch on promises, Promise.all, Promise.allSettled and wrappers. Explanation and output.Open example →js// Method 1: Async/await with try-catch async function fetchData() { try { const response = await fetch('https://api.example.com/data');
- 05Global Error HandlingIntermediateSet up global error handling in JavaScript with window error and unhandledrejection events, Node process handlers and an error logger. Explanation and output.Open example →js// Method 1: Window error handler window.addEventListener('error', function(event) { console.error('Global error:', event.message); console.error('File:', event.filename);
- 06Error LoggingIntermediateBuild error loggers in JavaScript: a simple JSON logger, structured logs with metadata, log levels and an aggregator that counts errors. Explanation and output.Open example →js// Method 1: Simple error logger class ErrorLogger { log(error, level = 'error') { const logEntry = {
- 07Error Retry LogicIntermediateWrite retry logic in JavaScript: simple retries, exponential backoff, retries with conditions and a RetryHandler class with demos. Explanation and output.Open example →js// Method 1: Simple retry async function retryOperation(fn, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try {
- 08Defensive ProgrammingIntermediateLearn defensive programming in JavaScript: check input, guard null values, set defaults, validate types and ranges, and use fallbacks. Explanation and output.Open example →js// Method 1: Input validation function processUserInput(input) { if (typeof input !== 'string') { throw new TypeError('Input must be a string');
- 09Error RecoveryAdvancedRecover from errors in JavaScript with fallback values, retry then fallback, a circuit breaker, graceful degradation and timeouts. Explanation and output.Open example →js// Method 1: Fallback values function fetchWithFallback(url, fallback) { return fetch(url) .then(response => response.json())
- 10Error TestingIntermediateTest error handling in JavaScript: check that code throws, check the error type, mock failures, test async errors and many scenarios. Explanation and output.Open example →js// Method 1: Test error throwing function testErrorThrowing() { try { throw new Error('Test error');