How can I catch a rendering error / missing template in node.js using express.js?
I have code like this that will render a jade template without a route defined. Think of this like the express.static but it calls res.render with the url.
app.use(function (req, res, next) {
try {
res.render(req.url.substring(1), { title: "No Controller", user: req.session.user });
} catch (err) {
console.log(err)
next();
}
});
The problem is that res.render() isn't throw开发者_开发技巧ing an error. Instead it is rendering an error page. Is there a way to detect a missing template or any rendering errors?
A better way to do it, instead of requiring fs
and having another callback, would be to use render's callback :
res.render(my_page_im_not_sure_it_exists, {}, function(err, html) {
if(err) {
res.redirect('/404'); // File doesn't exist
} else {
res.send(html);
}
});
Use fs.exists(p, [callback])
to check if the file exists before calling res.render
http://nodejs.org/docs/latest/api/fs.html#fs_fs_exists_path_callback
Node 0.6.x and older
Use path.exists(p, [callback])
to check if the file exists before calling res.render
http://nodejs.org/docs/v0.6.0/api/path.html#path.exists
Similar to @Augustin Riedinger's answer, the same applies when rendering to variable using renderFile
:
var html = jade.renderFile('path/to/file.jade', context, function(err, html) {};
You could use fs.open
to check if the template exists.
app.use(function (req, res, next) {
fs.open(__dirname + '/views/' + req.url.substring(1) + '.jade', 'r', function (err) {
if(err) {
console.log(err);
return next();
}
res.render(req.url.substring(1), { title: "No Controller", user: req.session.user });
}
});
精彩评论