Facebook Pixel
Step-by-Step Guide

How to do Error Handling in JavaScript

A step-by-step guide on how to handle errors in JavaScript using try-catch-finally, custom error classes, and error handling patterns for both synchronous and asynchronous code.

Understand the Types of JavaScript Errors

JavaScript has several built-in error types. SyntaxError occurs when code is grammatically invalid and is caught by the parser before execution. ReferenceError occurs when accessing a variable that does not exist. TypeError occurs when a value is not of the expected type, like calling null as a function. RangeError occurs when a value is outside the allowed range. URIError occurs with malformed URI functions. All these inherit from the base Error class.

Use try-catch for Synchronous Error Handling

Wrap code that might throw an error inside a try block. If an error is thrown anywhere inside the try block, execution immediately jumps to the catch block, skipping all remaining code in try. The catch block receives the thrown error object as a parameter. After the catch block finishes, execution continues normally after the try-catch structure. Unhandled errors propagate up the call stack and if nothing catches them, the program crashes.

Use the finally Block for Cleanup

Add a finally block after catch to run cleanup code that must execute regardless of whether an error occurred. The finally block runs whether the try block completed normally, threw an error that was caught, or even if a caught error was re-thrown in the catch block. Use finally for releasing resources like closing database connections, stopping loading spinners, or releasing locks that must always be cleaned up.

Create Custom Error Classes

Extend the built-in Error class to create custom error types specific to your application domain. Pass the error message to super in the constructor to set the inherited message property. Set the name property to the class name for clear identification. Add custom properties relevant to the error context such as statusCode for HTTP errors or field for validation errors. Custom errors allow you to use instanceof checks to handle different error types differently.

Rethrow Errors Selectively

Inside a catch block, you can choose to handle only certain types of errors and rethrow the rest. Use instanceof to check the error type. If the error is one you can handle, handle it and continue. If it is not, call throw with the caught error to rethrow it so it propagates up to a higher-level handler. This pattern lets each layer of code handle only the errors relevant to its responsibility.

Handle Errors in Promises

Errors thrown inside Promise executors or in then callbacks automatically reject the Promise. Attach a catch handler to the Promise chain to handle rejections. The catch handler receives the rejection reason. Errors that are not caught in the Promise chain become unhandled Promise rejections, which in modern environments terminate the Node.js process or log prominent warnings in browsers.

Handle Errors in Async Await Functions

Errors thrown in awaited Promises surface as thrown exceptions in the async function, allowing you to catch them with standard try-catch blocks. Wrap await expressions in try-catch when you want to handle errors locally. Alternatively, add a catch call to the Promise before awaiting it, converting a rejection into a resolved value like null. You can also let errors propagate by not catching them, causing the returned Promise of the async function to reject.

Implement Global Error Handlers

For errors that escape all local catch blocks, set up global error handlers. In browsers, listen for the error event on the window object for synchronous errors and the unhandledrejection event for unhandled Promise rejections. In Node.js, listen for uncaughtException and unhandledRejection events on the process object. Use global handlers to log errors to a monitoring service and perform graceful cleanup before the process terminates.

Ready to master this completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.