Skip to content

Error Handling

Writing resilient code is an essential skill for every developer. Proper error handling helps prevent unexpected crashes in your application and makes debugging easier when something goes wrong. In this article, we’ll cover some important techniques and tools to handle errors effectively.

The try...catch block is one of the most essential constructs for handling runtime errors in JavaScript. It allows you to try a block of code and handle any potential exceptions that might occur.

try {
// Code that may throw an error
const result = someFunction();
console.log(result);
} catch (error) {
// Handle the error
console.error("An error occurred:", error.message);
}

Here try block contains the code that might throw an error. The catch block is executed if an error occurs. It gives you access to the caught error, which is generally an Error object. se console.error() or other logging to track errors effectively.

JavaScript also provides the finally block to execute code regardless of whether an error occurred or not. This is particularly useful for cleanup activities such as closing resources or resetting application states.

try {
const data = fetchData();
console.log(data);
} catch (error) {
console.error("Fetch failed:", error.message);
} finally {
console.log("Cleanup actions performed.");
}

Ensure that important code runs even if an error occurs.On frontend reset variables or UI loading states. While building backend services close database connections or release resources in the finally block.

At times, the built-in error types may not fully capture the intent or cause of an error in your code. You can define and throw custom errors using the Error class.

Custom errors allow you to define clear, meaningful error messages tailored to your application logic, they can also help differentiate between different types of errors when debugging.

class CustomError extends Error {
constructor(message) {
super(message);
this.name = "CustomError";
}
}
function performAction(action) {
if (!action) {
throw new CustomError("Action is required.");
} // Logic to perform the action
}
try {
performAction(null);
} catch (error) {
if (error instanceof CustomError) {
console.error("Custom error caught:", error.message);
} else {
console.error("An unknown error occurred:", error.message);
}
}

Effective debugging is an important part of error handling. Modern browsers come equipped with powerful developer tools to help you diagnose and fix errors.

Use the following steps as standard steps to debug issues.

  1. Open Developer Tools:

In most browsers, press F12 or Cmd+Option+I (Mac) / Ctrl+Shift+I (Windows) to open the developer tools.

  1. Use the Console:

The console lets you view logged data using statements like console.log(), console.warn(), and console.error(). Inspect stack traces to understand where the error originated.

  1. Set Breakpoints:

Use the “Sources” panel to pause execution at specific lines of code. This allows you to inspect the state of variables at runtime.

  1. Network Tab:

Debug API requests in the “Network” tab. Check the status of responses, headers, or payload data to identify potential server-side issues.

  1. Error Details:

Watch for detailed error messages in the console. Some errors may include links to documentation or stack traces for additional context.