在 express 中,如何在满足条件时路由到自定义错误模板?

In express, how do I route to a custom error template when a condition is met?

在我的 select 语句中,如果来自 URL 的参数不正确,我想将用户发送到自定义错误模板。

我已尝试设置渲染,但传递的参数不起作用。

#routes.js
router.get('/select-id/', function(req, res) {
    var id = req.query.id;
    if(id && id.match(/^[0-9]+$/) != null){
        mc('SELECT * FROM tasks where ID = ' + id, function (error, results, fields) {
         if (error) throw error;
          res.render('pug-select-all', {
            title: 'Results',
            data: results
          });
        });
    }
    else {
        res.render('error', {status: 500, stack: 'error'});
    }
});
#error.pug
extends layout

block content
  h1= message
  h2= error.status
  pre #{error.stack}

我尝试过不同的方法,但我总是在 routes.js 或 pug 模板上遇到错误。如果我像上面的代码一样保留它,我会在 error.pug

中得到 Cannot read property 'status' of undefined

查看文档,您应该将响应对象发送为:

res.render('error', { "error": {status: 500, stack: 'error' } });

在您的pug模板中,作为一级成员访问它,例如:

#error.pug
extends layout

block content
  h1= message
  h2= status
  pre #{stack}

这就是我的工作方式

res.status(404).render('errorPage', {
  title: '404 - page nt found!'
});

根据您的需要,它可能是

res.status(500).render('error', {
  status: 500, 
  stack: 'error'
});