在下面的代码中,我想检查标头是否有效,然后停止读取流,并将错误发送回客户端(通过我的 ErrorHandler 函数)。我在控制台中看到以下内容:
UnhandledPromiseRejectionWarning:错误:请检查您的列标题。
这是为什么?
uploadExercisesViaFile = async (
req: Request,
res: Response,
next: NextFunction
) => {
try {
let checker = (arr, target) => target.every((v) => arr.includes(v));
const columns = ["name", "link", "description"];
const results = [];
let errors: string[] = [];
const parseCSV = parseString(req.file.buffer.toString(), {
headers: true,
maxRows: 5,
})
.on("headers", (header) => {
if (!checker(header, columns)) {
errors.push("Please check your column headers.");
parseCSV.end();
}
})
.on("data", async (row) => {
console.log(row);
results.push(row);
})
.on("error", (error) => {
errors.push(error.message);
})
.on("end", async (rowCount) => {
// Check if errors
if (errors.length > 0) {
console.log(errors);
throw new ErrorHandler(400, errors[0]);
}
// Upload
const uploadedExercises = await Exercises.batchUploadExercise(
results.map((r) => {
return { ...r, access: req.body.access, coach: req.user.id };
})
);
res.status(200).json({ rowCount: rowCount });
return;
});
} catch (e) {
next(e);
}
};