1

I have a method in Node JS which reads a file containing JSON data and finds a product with specific ID.

async getProductwithId(id) {
        try {
            let rawData = fs.readFileSync("data/products.json");
            let data = JSON.parse(rawData);
            for (const element of data) {
                if (id === element.productId) {
                    return element;
                }
            }
            throw new ProductDoesNotExistError("No Such Product Exists");
        } catch (error) {
            throw new FileReadingError("Error Reading File");
        }
    }

where ProductDoesNotExistError and FileReadingError both extend Error. I have put try/catch for the fs.readFileSync()

the problem is even if i have ProductDoesNotExistError, it's sending FileReadingError. I want to handle here the FileReadingError only and not ProductDoesNotExistError. I will let the callling function handle the ProductDoesNotExistError. How do I achieve this functionality.

1 Answer 1

2

Since in your catch block you throw a new instance of FileReadingError, all caught errors will result in the latter. You could either put the try/catch just around the readFileSync operation or check the type of the error in your catch block (also there's no need for async as the code inside the method is not async - e.g. your not using fs.promises.readFile()):

getProductwithId(id) {
    let rawData;
    try {
        rawData = fs.readFileSync("data/products.json");
    } catch (error) {
        throw new FileReadingError("Error Reading File");
    }
    const data = JSON.parse(rawData);
    for (const element of data) {
        if (id === element.productId) {
            return element;
        }
    }
    throw new ProductDoesNotExistError("No Such Product Exists");
}

or you do:

getProductwithId(id) {
    try {
        const rawData = fs.readFileSync("data/products.json");
        const data = JSON.parse(rawData);
        for (const element of data) {
            if (id === element.productId) {
                return element;
            }
        }
        throw new ProductDoesNotExistError("No Such Product Exists");
    } catch (error) {
        if (error instanceof ProductDoesNotExistError) {
            // rethrow ProductDoesNotExistError error
            throw error;
        }
        throw new FileReadingError("Error Reading File");
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.