如何在生产环境下关闭Node.js Express(ejs模板引擎)错误提示?

6
当我在开发服务器上遇到错误时,Express 会将 traceback 作为响应发送。但是,在生产环境下这样做是不好的。我不希望任何人看到我的 traceback。
如何关闭此功能?
注意:我正在使用 EJS 作为模板引擎 - 这可能是原因,而不是 Express。例如,当我在 ejs 模板中有未定义的变量时,ejs 会渲染 traceback 并在白色页面上向用户显示它。

你正在使用哪个版本的Express? - Leonid Beschastny
2个回答

11

最新版本的Express使用智能默认错误处理程序。

开发 模式下,它会将完整的堆栈跟踪发送回浏览器,而在 生产 模式下,它只会发送 500 Internal Server Error

为了充分利用它,您应该在运行应用程序之前设置正确的 NODE_ENV

例如,要在生产模式下运行应用程序:

NODE_ENV=production node application.js

但如果你不喜欢这种默认行为,你可以定义自己的错误处理程序:

app.use(function(err, req, res, next){
  console.error(err);
  res.status(500);
  res.render('error');
});

注意,错误处理程序必须是链中的最后一个中间件,因此应该在您的application.js文件底部定义。
如果您需要更多信息,请参阅:

6

因此,错误可能来自于express或ejs。在以下情况下:

  1. Express error : Use custom error handling to override the default behaviour. Simply don't send back the error. Read about it on the documentation page. Or you can use already existing middleware such errorhandler like Leonid said to override it.
  2. Template error : Due to jade/ejs etc. Again handle the errors instead of default behaviour which is to send them to client. Use a callback and check for errors. If there is don't display them, instead show an error page.

    res.render(your_template, {}, function(err, html) {
        if(err) {
            res.redirect('/error');
        } else {
            res.send(html);
        }
    });
    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接