Mastering Advanced Error Handling in JavaScript: try, catch, and finally - CodingQue

Advanced Error Handling in JavaScript

Proper error handling is essential for building reliable applications. JavaScript provides a try, catch, and finally structure to handle errors in a way that keeps the codebase stable and predictable. Let’s look at some advanced techniques with detailed examples.

Enhanced try and catch Usage

We often use try and catch blocks to wrap code where errors might occur. Additionally, we can create custom error messages to provide meaningful feedback.

try {
    let user = { name: "John" };
    if (!user.email) {
        throw new Error("User email not found!");
    }
} catch (error) {
    console.error("Custom Error:", error.message);
}

Example: Throwing Custom Errors

Here, we manually throw an error when the user email is missing. This allows us to create custom conditions for error handling and display meaningful messages to users or developers.

function getUserAge(age) {
    try {
        if (age < 0) {
            throw new RangeError("Age cannot be negative");
        }
        console.log("User's age:", age);
    } catch (error) {
        console.error("Caught an error:", error.message);
    }
}

getUserAge(-5); // Output: Caught an error: Age cannot be negative

Handling Errors in Asynchronous Code

For asynchronous code, such as promises and async/await, we need to handle errors differently. Wrapping async code in try/catch blocks ensures proper error handling in async functions.

async function fetchData() {
    try {
        let response = await fetch("https://api.example.com/data");
        if (!response.ok) throw new Error("Network response was not ok");
        let data = await response.json();
        console.log(data);
    } catch (error) {
        console.error("Fetch error:", error.message);
    }
}

fetchData();

The finally Block

The finally block is used to execute code after the try and catch blocks, regardless of the outcome. This is useful for cleanup tasks or resetting states.

function cleanUpProcess() {
    try {
        console.log("Processing...");
        throw new Error("An unexpected error");
    } catch (error) {
        console.error("Error caught:", error.message);
    } finally {
        console.log("Cleaning up resources");
    }
}

cleanUpProcess();
// Output:
// Processing...
// Error caught: An unexpected error
// Cleaning up resources

Error Handling with Multiple Catch Statements

JavaScript does not support multiple catch statements, but we can use if/else statements to handle different types of errors within the catch block.

try {
    let data = JSON.parse("Invalid JSON String");
} catch (error) {
    if (error instanceof SyntaxError) {
        console.error("JSON Syntax Error:", error.message);
    } else {
        console.error("General Error:", error);
    }
}

Example: Handling Network Errors

Here is how we can handle network errors while fetching data from an API. We check for different types of errors based on the response status.

async function fetchUserData() {
    try {
        const response = await fetch("https://api.example.com/userdata");
        if (response.status === 404) {
            throw new Error("User not found");
        }
        if (!response.ok) {
            throw new Error("Network response error");
        }
        const data = await response.json();
        console.log(data);
    } catch (error) {
        console.error("Network error:", error.message);
    } finally {
        console.log("Request completed");
    }
}

fetchUserData();
Previous Next
Modern Footer