我在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()尝试/捕获了
问题是即使我有ProductDoesNotExistError,它也会发送FileReadingError。我只想在这里处理FileReadingError而不是ProductDoesNotExistError。我将让callling函数处理ProductDoesNotExistError。如何实现此功能。
由于在catch块中引发的新实例FileReadingError
,因此所有捕获的错误都会导致后者。您可以将其放在操作try/catch
周围,也可以readFileSync
在catch块中检查错误的类型(也不需要,async
因为方法中的代码不是异步的-例如,您未使用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");
}
或者你这样做:
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");
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句