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 throwing an error. Instead it is rendering an error page. Is there a way to detect a missing template or any rendering errors?
For error handling, we have the next(err) function. A call to this function skips all middleware and matches us to the next error handler for that route. Let us understand this through an example. var express = require('express'); var app = express(); app.
render() method is used for returning the rendered HTML of a view using the callback function. This method accepts an optional parameter that is an object which contains the local variables for the view.
The res. render() function is used to render a view and sends the rendered HTML string to the client.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With