【发布时间】: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