5

我目前通过在 routes.js 中包含这一行,将每个页面路由到我的 pagesController 中,这些页面在以前的路由中找不到:

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

如果找不到,我有想法让我的 PagesController 处理服务 404:

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;
};

但我的想法失败了。无法捕获错误,因此仍然会提供致命错误。我应该在渲染调用中附加一个 fn 吗?有什么论据?它是如何工作的?(/简单的问题)。

4

1 回答 1

6

它可能看起来像这样:

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' });
  }
};
于 2013-12-03T10:31:18.037 回答