Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 throwing an error. Instead it is rendering an error page. Is there a way to detect a missing template or any rendering errors?

like image 219
respectTheCode Avatar asked Sep 02 '11 13:09

respectTheCode


People also ask

How can you deal with error handling in Express JS?

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.

What is render in Express JS?

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.

What does res render do in node JS?

The res. render() function is used to render a view and sends the rendered HTML string to the client.


2 Answers

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);     } }); 
like image 52
Augustin Riedinger Avatar answered Oct 19 '22 16:10

Augustin Riedinger


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

like image 41
respectTheCode Avatar answered Oct 19 '22 18:10

respectTheCode