I'm using Express.js and swig templates to build a web application. The problem is that when the swig rendering fails (for instance when the template is faulty), I can't catch the error which it throws and node crashes.
Specifically, the error comes when I use the stringGenerator function to return an object and reference the object the wrong way. I get an 'Unexpected key' error thrown which I can't seem to catch.
app.get('/', function (req, res) {
try {
res.render('index', { 'stringFunction': stringGenerator });
} catch(err) {
console.error(err);
}
});
How do I catch the error which swig throws at res.render.
One solution is to use express-domain-middleware
. That allows you to catch errors in routes and deal with them with a normal Express error handler:
app.use(require('express-domain-middleware'));
...your routes...
// error handler
app.use(function(err, req, res, next) {
console.error('An error occurred:', err.message);
res.send(500);
});
This doesn't strictly deal with Swig errors only though, but I haven't found another way besides using domains to catch Swig errors.