5

I am currently routing every page to my pagesController that cannot be found in previous routes by including this line in routes.js:

this.match('/:page', { controller: 'pages', action: 'show' });

I had the idea to let my PagesController handle serving a 404 if not found:

PagesController.show = function() {
    var page = this.param('page');
    if(page != undefined){
        page = page.replace(".html","");        
        try {
            this.render("./"+page);
        } catch(error){ //Failed to look up view -- not working at the moment =(
            this.redirect({action : "404"});
        };
    }

    return;
};

But my idea is failing. The error cannot be caught, so the fatal still gets served. Should I append a fn to the render call? With what arguments? How does it work? (/simple questions).

Spork
  • 1,631
  • 1
  • 21
  • 37

1 Answers1

6

It might look something like this:

PagesController.show = function() {
  var self  = this;
  var page  = this.param('page');

  if (page !== undefined) {
    page = page.replace('.html', '');
    this.render("./" + page, function(err, html) {
      if (! err)
        return self.res.send(html);
      self.redirect({ action : '404' });
    });
  } else {
    // this will probably never be called, because `page`
    // won't be undefined, but still...
    this.redirect({ action : '404' });
  }
};
robertklep
  • 198,204
  • 35
  • 394
  • 381
  • Thank you very much. It works very nicely! The standardized coding style (single quotes, !==) also woke me up. Much appreciated. – Spork Dec 03 '13 at 11:03
  • Ah, I hit a snag. "return self.res.send(html);" is inside of function(err, html), so it actually doesn't stop the PageController.show function. In the end, as is, every request will still be redirected to 404. The last line should probably go, right? – Spork Dec 03 '13 at 12:26
  • Done locally too, thanks! I scared some coworkers after a commit where everything went to 404. Everything is nice and clean again – Spork Dec 03 '13 at 12:32