首页 > 解决方案 > 在 express 中,当满足条件时,如何路由到自定义错误模板?

问题描述

在我的选择语句中,如果 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 模板上遇到错误。如果我像上面的代码一样保留它,我会Cannot read property 'status' of undefined进入 error.pug

标签: node.jsexpresserror-handlingpug

解决方案


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

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

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

#error.pug
extends layout

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

推荐阅读