我具有此功能:
function createDevis(invoice, path) {
const file = fs.createWriteStream(path);
file.on("error", function (error) {
logger.error("Inside file.on inside createDevis function");
logger.error(error);
file.end();
});
doc.pipe(file);
}
它在这里叫:
models.operation_sav
.findByPk(devisInformation.opSavId, { include: [{ all: true }] })
.then((operationSavFound) => {
if (operationSavFound !== null) {
// When this function throws an error, I would like to also handle it in the catch block
createDevis(devisData, "./generatedDocuments/devis.pdf");
} else {
res.status(400).json({
tag: "Operation Sav Not found",
message: error.message,
});
}
})
.catch((error) => {
logger.error(error);
res.status(400).json({
tag: "The devis has not been generated!",
message: error.message,
});
});
我希望在catch块中处理所有错误。但是,函数createWriteStream
在内部处理错误的方式不允许我在catch块内捕获错误:
const file = fs.createWriteStream(path);
file.on("error", function (error) {
logger.error("Inside file.on inside createDevis function");
logger.error(error);
file.end();
});
这会在响应http请求时出现问题,也使代码中的错误处理变得不那么直接。
我尝试在file.on
内抛出错误:
file.on("error", function (error) {
logger.error("Inside file.on inside createDevis function");
logger.error(error);
console.log(error);
file.end();
throw new Error("Error inside createWriteStream");
});
为了像在catch块中的其他错误一样捕获它。但是,这没有任何改变。