如何关闭Node.js Express(ejs模板引擎)生产的错误? [英] How do I turn off Node.js Express (ejs template engine) errors for production?
问题描述
当我处于开发服务器上并且出现错误时,Express会作为响应发送回溯。
When I'm on a development server and there is an error, Express sends the traceback as a response.
但是,这不适合生产。我不想让任何人看到我的追踪。
However, this is not good for production. I don't want anyone seeing my trackback.
如何关闭?
注意:使用EJS作为模板引擎 - 这可能是原因,而不是表达。例如,当我在ejs模板中有一个未定义的变量时,ejs将呈现回溯,并在白页上显示给用户。
Note: I'm using EJS as a template engine - this may be the cause, and not express. When I have an undefined variable in the ejs template, for example, ejs renders the traceback and displays it to the user on a white page.
推荐答案
最新版本的Express使用智能默认错误处理程序。
The latest version of Express use smart default error handler.
在开发
模式下,它发送完整堆栈追溯到浏览器,而在生产
模式中,它只发送 500内部服务器错误
。
In development
mode it sends full stack trace back to the browser, while in production
mode it sends only 500 Internal Server Error
.
为了利用它,您应该在运行应用程序之前设置正确的 NODE_ENV
。
To take advantage of it you should set proper NODE_ENV
before running your application.
例如,要在生产模式下运行应用程序:
For example, to run your app in production mode:
NODE_ENV=production node application.js
但是,如果您不喜欢此默认行为,您可以定义自己的错误处理程序:
But if you don't like this default behavior, you could define your own error handler:
app.use(function(err, req, res, next){
console.error(err);
res.status(500);
res.render('error');
});
请注意,错误处理程序必须是链中的最后一个中间件,因此应该在底部定义您的 application.js
文件。
Note that error handler must be the last middleware in chain, so it should be defined in the bottom of your application.js
file.
如果您需要更多信息,请参阅:
If you need more information, see:
- Express official documentation
- Blog post about error handling in Express
这篇关于如何关闭Node.js Express(ejs模板引擎)生产的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!