Error Handling in JavaScript

Let's see an example:

                                      
                                        function divideNumbers(a, b) {
                                            try {
                                                if (b === 0) {
                                                    throw new Error('Cannot divide by zero');
                                                }
                                        
                                                const result = a / b;
                                                return result;
                                            } catch (error) {
                                                console.error('Error:', error.message);
                                                // You can perform additional error handling or logging here
                                                return 'Error occurred';
                                            }
                                        }
                                        
                                        // Example usage
                                        console.log(divideNumbers(10, 2)); // Output: 5
                                        console.log(divideNumbers(8, 0));  // Output: Error occurred, with console error: Error: Cannot divide by zero                                                                                                                                                                                                                                                                     
                                      
                                    

In this example:


  • This is the code that potentially raises the exception, and it has to be placed in a try block.
  • If an exception roams then catch block is executed and the error is stored in error variable.
  • If the value does not exist or is of an unexpected type, you can then manage the exception, write a log or do whatever necessary.

As you may remember, in using try-catch, the catch block will have a priority over the finally block. .. catch is very handy if dealing with synchronous exceptions.

For asynchronous errors like the ones mentioned in promises callbacks you would normally use the catch of promises or pass an error callback.

                                      
                                        function fetchData() {
                                            return new Promise(function(resolve, reject) {
                                                // Simulating an asynchronous operation
                                                setTimeout(function() {
                                                    const success = Math.random() > 0.5;
                                                    if (success) {
                                                        resolve('Data fetched successfully');
                                                    } else {
                                                        reject(new Error('Failed to fetch data'));
                                                    }
                                                }, 1000);
                                            });
                                        }
                                        
                                        // Using try...catch with async/await
                                        async function fetchDataWrapper() {
                                            try {
                                                const result = await fetchData();
                                                console.log(result);
                                            } catch (error) {
                                                console.error('Error:', error.message);
                                            }
                                        }
                                        
                                        fetchDataWrapper();                                                                                                                                                                                                                                                                                                          
                                      
                                    

In the example above, the try...catch block is used with async/await to handle errors in an asynchronous operation.