I’m working on a web app with express that uses postgres as the backed database and trying to catch possible errors during the loading of data in the database but i have problems catching errors generated in the pool.connect function. I followed the code example in this page but i get a “Cannot set headers after they are sent to the client” when there is an error within the function. How can i solve it?
I investigated the problem and i think that it is related to the fact that some code is still executed even after one of the “return res.redirect(“/edit/upload”);” commands is called but at this point i don’t know the best approach to catch all the errors within the function.
module.exports.uploadDocument = async (req, res) => {
let data = [{user_code: req.body.code, document_date: req.body.date, document_type: req.body.doctype, company: req.body.company}]
const csv = new ObjectsToCsv(data);
let document_name = "document_".concat(req.session.passport.user, "_", req.body.identifier, ".csv");
let postings_name = "postings_".concat(req.session.passport.user, "_", req.body.identifier, ".csv");
csv.toDisk("./public/uploads/".concat(document_name));
await pool.query("create temp table temp_document (user_code integer not null, document_date date not null, document_type varchar(4) not null, company varchar(4) not null); create temp table temp_postings (gl_code varchar(10) not null, position integer not null, amount numeric(20, 4) not null, cost_center varchar(4), reg_date date not null, acc_center varchar(4), eff_date date not null, order_num integer, discount numeric(5,4), pay_mode varchar(4), suppl_code varchar(4), location varchar(4), country_code varchar(4), document_num integer);")
pool.connect(function (err, client, done) {
var stream = client.query(copyFrom("coy temp_postings(gl_code, position, amount, cost_center, reg_date, acc_center, eff_date, order_num, discount, pay_mode, suppl_code, location, country_code) FROM STDIN WITH (FORMAT CSV, HEADER, DELIMITER ';')"));
var fileStream = fs.createReadStream(`./public/uploads/${postings_name}`);
fileStream.on('error', () => {
req.flash("error", "Error with copy");
return res.redirect("/edit/upload");
})
stream.on('error', () => {
req.flash("error", "Error with copy");
return res.redirect("/edit/upload");
})
fileStream.pipe(stream);
var stream = client.query(copyFrom("copy temp_document(user_code, document_date, document_type, company) FROM STDIN WITH (FORMAT CSV, HEADER, DELIMITER ',')"));
var fileStream = fs.createReadStream(`./public/uploads/${document_name}`);
fileStream.on('error', () => {
req.flash("error", "Error with copy");
return res.redirect("/edit/upload");
})
stream.on('error', () => {
req.flash("error", "Error with copy");
return res.redirect("/edit/upload");
})
fileStream.pipe(stream);
client.query("call data_loading();")
.then (() => {
fs.unlinkSync(`./public/uploads/${postings_name}`);
fs.unlinkSync(`./public/uploads/${document_name}`);
res.redirect("/");
})
})
}