I'm currently developing a Node/Express application and I want it to display a 404 page if a promise function doesn't resolve.
This is my approach:
app.get("/projects", t("projects", function(req, res) {
res.header("Cache-Control", "private, max-age=0, no-cache, no-store");
return projects.list(req.user, req.query)
.then((projects) => (Object.assign(projects, { company_name: req.user.company_name })))
.catch(() => res.status("404").send(""));
}));
However, this causes the app to crash with the error
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
.
Is there a way to make it return a 404 without crashing the app only when the promise rejects?
Just for reference, the projects.list
function is quite simple, it just performs a database query and returns an object.
function list(user, query_params) {
const folder = query_params.folder || "all";
return entity.User.listedProjects(user.id, filter_by)
.then((projects) => {
if (folder !== null && !projects.some(t => t.current)) {
return Promise.reject();
}
return {
"projects": projects,
"active_folder": folder
};
});
}
UPDATE: here's the definition of the t
function as requested:
function t(template_name, get_additional_params, options={}) {
return function(req, res) {
if (!req.user && !options.do_not_require_login) return res.redirect("/login?redirect=" + encodeURIComponent(req.originalUrl));
if (!get_additional_params) {
get_additional_params = (() => Promise.resolve({}));
}
get_additional_params(req, res)
.then(function(additional_params) {
if (additional_params && "_redirect" in additional_params) {
return res.redirect(additional_params._redirect);
}
const standard_params = {
"error": req.flash("error"),
};
const params = Object.assign({}, additional_params, standard_params);
res.render(template_name + ".html", params);
})
.catch(utils.fail(req, res));
};
}