【发布时间】:2020-12-11 17:36:53
【问题描述】:
我正在为 node JS 和 Express 开发一个 3 层架构后端。
我必须读取包含 JSON 数据的文件并使用 REST 使用 HTTP 发送
我的问题是从 fs.readFile 抛出的错误没有被传播到上层,尽管使用了 throw。但是该代码适用于 fs.readFileSync。
dao.js
const fs = require("fs");
class DAO {
async getAllProducts() {
// try {
// fs.readFileSync("products.json");
// } catch (error) {
// throw new Error("Error Reading File");
// }
fs.readFile("./products.json", (err, data) => {
if (err) {
throw new Error("Error Reading File");
} else {
let d = JSON.parse(data);
return d;
}
});
}
}
module.exports = new DAO();
service.js
const dao = require("../data/dao");
class Service {
async getAllProducts() {
try {
return await dao.getAllProducts();
} catch (error) {
throw error;
}
}
}
module.exports = new Service();
product.js
const express = require("express");
const router = express.Router();
const service = require("../service/service");
const Response = require("../models/Response");
router.get("/", async (req, res) => {
try {
const data = await service.getAllProducts();
res.status(200).send(new Response(200, "Success", null, data));
} catch (error) {
res.status(500).send(new Response(500, "Failure", error.message, null));
}
});
module.exports = router;
点击 http://localhost:3000/api/products 并使用 fs.readFileSync 方法,o/p 符合预期
{
"statusCode": 500,
"status": "Failure",
"message": "Error Reading File",
"data": null
}
但是在使用 fs.readFile 时,o/p 很奇怪
{
"statusCode": 200,
"status": "Success",
"message": null
}
控制台输出如下
throw new Error("Error Reading File");
^
Error: Error Reading File
at ReadFileContext.callback (C:\Users\a\b\c\d\data\dao.js:12:11)
at FSReqCallback.readFileAfterOpen [as oncomplete] (fs.js:264:13)
我的猜测是因为 readfile 是一个 async fn,所以它会导致问题,但为了解决这个问题,我在任何地方都使用了 async/await,所以应该不会有问题。不知道哪里出错了。
非常感谢任何帮助
【问题讨论】:
标签: node.js express error-handling fs