【问题标题】:handling multiple errors in Node js处理 Node js 中的多个错误
【发布时间】:2020-12-11 19:02:08
【问题描述】:

我在 Node JS 中有一个方法,它读取包含 JSON 数据的文件并找到具有特定 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");
        }
    }

其中 ProductDoesNotExistError 和 FileReadingError 都扩展了 Error。我已经为 fs.readFileSync() 放了 try/catch

问题是即使我有 ProductDoesNotExistError,它也会发送 FileReadingError。我只想在这里处理 FileReadingError 而不是 ProductDoesNotExistError。我将让调用函数处理 ProductDoesNotExistError。如何实现此功能。

【问题讨论】:

    标签: javascript node.js error-handling try-catch


    【解决方案1】:

    由于在你的 catch 块中你抛出了一个新的 FileReadingError 实例,所有捕获的错误都将导致后者。您可以将try/catch 放在readFileSync 操作周围,或者检查catch 块中的错误类型(也不需要async,因为方法内的代码不是异步的 - 例如你不使用@ 987654325@):

    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");
    }
    

    或者你这样做:

    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");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-05-24
      • 2018-06-22
      • 1970-01-01
      • 2014-08-22
      • 2016-04-07
      • 2021-08-12
      • 2016-05-08
      • 2021-04-15
      • 2018-03-10
      相关资源
      最近更新 更多